Leetcode:435. Non-overlapping Intervals (week 9)

Description:

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:
You may assume the interval’s end point is always bigger than its start point.
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.

解題思路及算法分析

題意是要移除重疊區間,結果返回爲移除的最小區間數。本題可用貪心算法解決,以每個元素的end爲關鍵元素排序,end相等的情況下,按start升序排序。本題跟“只有一個場地,要安排儘量多的活動“類似。貪心規則:儘量安排結束時間早的活動。如果後面的活動與已經安排好的兼容,則加入集合。時間複雜度爲O(n).
注意的是排序時調用sort要自定義排序條件

代碼

/**
 * 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:
    static bool cmp(Interval a, Interval b) {
        if (a.end <= b.end) {
            if (a.end < b.end) {
                return true;
            }
            return a.start <= b.start;
        }
        return false;
    }
    int eraseOverlapIntervals(vector<Interval>& intervals) {
        int size = intervals.size();
        if(size == 0) {return 0;}
        int count = 0;//移除的區間數
        sort(intervals.begin(),intervals.end(),cmp);
        int g = intervals[0].end;//必須是排完序後的第一個區間
        for (int i = 1; i < size; i++) {
            if (intervals[i].start < g) {
                count++;
            } else g = intervals[i].end;
        }
        return count;
    }
};

或者可以將start排序,代碼如下

/**
 * 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<Interval>& intervals) {
        int size = intervals.size();
        if(size == 0) return 0;
        int count = 0;//移除的區間數
        int g = 0;
        sort(intervals.begin(),intervals.end(),[](Interval a, Interval b) {
            return a.start < b.start;
        });
        for (int i = 1; i < size; i++) {
            if (intervals[i].start < intervals[g].end) {
                count++;
                if (intervals[i].end < intervals[g].end) g = i;
            } else {
                g = i;
            }
        }
        return count;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章