greedy——435. Non-overlapping Intervals[medium]

題目描述

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.


給定多組區間,選擇刪除最少的區間,使得剩下的區間無交集。


解題思路


貪心算法,遍歷數組,發現重疊就刪去範圍較大的區間。爲什麼要去掉範圍最大的數組?因爲範圍大,就意味着能與更多的區間產生交集,所以要去掉。解題圖示:




整個步驟如下:

1、對intervals排序,以第一個元素上升排序,第一個相同則按第二個元素上升排序(使用sort排序,自己編寫排序函數com)

2、用tmp表示當前區間,如果與檢查到的區間有交集,tmp變爲兩者之間的較小者,計數器+1(表示應該刪去較大的那個)

3、無交集,tmp變爲檢查到的那個區間,繼續2(因爲已經排序了,可以保證一旦檢查到第一個與tmp無交集的區間,後面的也就不會有交集了)


代碼如下


/**
 * 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:
    bool static com(Interval a, Interval b) {
	if (a.start < b.start)
		return true;
	else if (a.start == b.start) {
		if (a.end < b.end)
			return true;

		return false;
	}

	return false;
}

bool inter(Interval a, Interval b) {
	if (a.end > b.start)
		return true;

	return false;
}

int eraseOverlapIntervals(vector<Interval>& intervals) {
    if(intervals.empty())
        return 0;
	sort(intervals.begin(), intervals.end(), com);
	int count = 0;
	
	Interval in = intervals[0];
	int j = 1;
	for (j; j < intervals.size(); j++) {
			if (inter(in, intervals[j])) {
			    	if(in.end > intervals[j].end)
					in = intervals[j];
				count++;
				continue;
			}
			in = intervals[j];
		}
	

	return count;
}
};


題外心得:

1、關於sort比較函數的傳入,sort默認是升序排序,要想使得降序,就應該這樣做:


bool com(int a,int b){

      return a > b;
}


也就是,讓sort認爲 a > b(返回true)時就是 a在b前面。

2、這兩道貪心算法都涉及了排序。

發佈了37 篇原創文章 · 獲贊 0 · 訪問量 7026
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章