算法分析与设计week07--435. Non-overlapping Intervals

435. Non-overlapping Intervals

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:
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

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.

Analyse

思路:跟场地安排问题类似(要求安排尽量多的活动),贪心算法,以每个元素的end为关键元素排序,end相等的情况下,按start升序排序。贪心规则:尽量安排结束时间早的活动。如果后面的活动与已经安排好的兼容,则加入集合。

查找重叠区间:判断方法是看如果前一个区间的end大于后一个区间的start,那么一定是重复区间,此时结果num加1,删掉一个区间。为了保证我们总体去掉的区间数最小,删掉那个end值较大的区间(使得后面有更宽裕的空间来排入更多的区间)。而在代码中,不需真正的删掉某一个区间,可以用cur指向当前留下来的区间,再与后面的区间作比较。

/**
 * 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) {

        if (intervals.size() == 0) {
            return 0;
        }

        sort(intervals.begin(), intervals.end(), [](Interval a, Interval b){
            return a.end < b.end || (a.end == b.end && a.start > b.start); 
        });

        int num = 0;
        Interval cur = intervals[0];

        for (int i = 1; i < intervals.size(); i++) {
            if (intervals[i].start < cur.end) {
                num++;
                cur = (intervals[i].end > cur.end) ? cur : intervals[i];
            } else {
                cur = intervals[i];
            }
        }

        return num;
    }
};

复杂度分析

时间复杂度:O(nlogn)
空间复杂度:O(1)

你可能感兴趣的:(算法设计与分析作业)