LeetCode 435. Non-overlapping Intervals C++

435. Non-overlapping Intervals

Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.

Note:
1.You may assume the interval’s end point is always bigger than its start point.
2.Intervals like [1,2] and [2,3] have borders “touching” but they don’t overlap each other.
Example 1:

Input: [ [1,2], [2,3], [3,4], [1,3] ]

Output: 1

Explanation: [1,3] can be removed and the rest of intervals are non-overlapping.

Example 2:

Input: [ [1,2], [1,2], [1,2] ]

Output: 2

Explanation: You need to remove two [1,2] to make the rest of intervals non-overlapping.

Example 3:

Input: [ [1,2], [2,3] ]

Output: 0

Explanation: You don't need to remove any of the intervals since they're already non-overlapping.

Approach

  1. 贪心问题中最典型题之一区间问题,给多组区间,问去除掉最少的区间,使得剩余区间都不重叠,首先就会想到排序,将区间排序,因为我要们除掉的区间尽可能小,所以我尽量保存小区间,去除大区间,所以我们以右区间排序,从小到大,并且右区间相等时,按左区间从小到大排序,然后我们就维护左区间边界,当左区间边界小于下一个的区间的右边界的时候,就将左区间边界扩张为一个区间的左边界,当左区间边界大于下一个的区间的右边界的时候,我们要比较左区间边界与下一个区间的左边界大小,取最小的,这样我们可以容纳更多的区间而不重叠。

Code

 bool cmp(Interval &a, Interval &b) {
     if (a.start == b.start)return a.end < b.end;
     else return a.start < b.start;
 }
class Solution {
public:
    int eraseOverlapIntervals(vector& intervals) {
        if (intervals.size()<2)return 0;
        sort(intervals.begin(), intervals.end(), cmp);
        int left = intervals[0].end,cnt=1;
        for (int i = 1; i < intervals.size(); i++) {
            if (left <= intervals[i].start) {
                cnt++;
                left = intervals[i].end;
            }
            else {
                left = min(left, intervals[i].end);
            }
        }
        return intervals.size()-cnt;
    }
};

你可能感兴趣的:(LeetCode 435. Non-overlapping Intervals C++)