leetcode——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.

解析:利用貪心算法求解,假設在某個區域,有n個區間重疊,則顯然n個區間最後只能留下一個,而根據局部最優,勢必留下end最小的最有利。根據這個思路,事先將數組排序,然後不斷刪去區間即可,時間複雜度爲O(n).

class Solution {
public:
	static bool cmp(Interval& a, Interval& b)
	{
		return a.end < b.end;
	} 
	int eraseOverlapIntervals(vector<Interval>& intervals) {
		if(!intervals.size())	return 0;
		int num = 0;
		sort(intervals.begin(), intervals.end(), cmp);
		for(vector<Interval>::iterator i = intervals.begin(); i!=intervals.end(); i++)
			while(i != intervals.end()-1 && i->end > (i+1)->start)	
			{
				intervals.erase(i+1);
				num ++;
			}
		return num;
	}
};
不懂爲嘛,用迭代器寫的反而耗時更長。。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章