435. Non-overlapping Intervals



将其按照区间头排序。

要想删除最少,就相当于找到 最多组不相交的区间

每次选取时,只有三种情况:

若后面的区间与此区间不相交(touching也算不相交),则当前区间可选择,并把考察目标转向后面那个区间。

若后面的包含在当前区间内,则考察目标转向后面的那个区间。

若后面的与当前区间相交,则仍考察当前区间。且对比的区间看后面那个。

/**
 * Definition for an interval.
 * struct Interval {
 *     int start;
 *     int end;
 *     Interval() : start(0), end(0) {}
 *     Interval(int s, int e) : start(s), end(e) {}
 * };
 */
class Solution {
public:
    int eraseOverlapIntervals(vector& intervals) {
        sort(intervals.begin(), intervals.end(), [](const Interval &i1, const Interval &i2){
            return i1.start < i2.start;
        });
        int total = 0;
        int i = 0;
        int j = 1;
        while(i + j < intervals.size()){
            Interval cur = intervals[i];
            Interval next = intervals[i + j];
            if (next.start >= cur.end){
                total++;
                i = i + j;
                j = 1;
            }else if (cur.end >= next.end){
                i = i + j;
                j = 1;
            }else if (cur.end < next.end)
                j++;
        }
        if (i + j == intervals.size())
            total++;
        // for(int i = 0; i < intervals.size();){
        //     Interval cur = intervals[i];
        //     Interval next = intervals[i + 1]; // if has next
        //     if (next.start >= cur.end){
        //         total++;
        //         cur = next;
        //     }else if (cur.end >= next.end)
        //         cur = next;
        // }
        return intervals.size() - total;
    }
};




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