[LeetCode] Non-overlapping Intervals 非重疊區間
阿新 • • 發佈:2018-12-27
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.
這道題給了我們一堆區間,讓我們求需要至少移除多少個區間才能使剩下的區間沒有重疊,那麼我們首先要給區間排序,根據每個區間的start來做升序排序,然後我們開始要查詢重疊區間,判斷方法是看如果前一個區間的end大於後一個區間的start,那麼一定是重複區間,此時我們結果res自增1,我們需要刪除一個,那麼此時我們究竟該刪哪一個呢,為了保證我們總體去掉的區間數最小,我們去掉那個end值較大的區間,而在程式碼中,我們並沒有真正的刪掉某一個區間,而是用一個變數last指向上一個需要比較的區間,我們將last指向end值較小的那個區間;如果兩個區間沒有重疊,那麼此時last指向當前區間,繼續進行下一次遍歷,參見程式碼如下:
解法一:
class Solution { public: int eraseOverlapIntervals(vector<Interval>& intervals) { int res = 0, n = intervals.size(), last = 0; sort(intervals.begin(), intervals.end(), [](Interval& a, Interval& b){return a.start < b.start;}); for (int i = 1; i < n; ++i) { if (intervals[i].start < intervals[last].end) { ++res; if (intervals[i].end < intervals[last].end) last = i; } else { last = i; } } return res; } };
我們也可以對上面程式碼進行簡化,主要利用三元操作符來代替if從句,參見程式碼如下:
解法二:
class Solution { public: int eraseOverlapIntervals(vector<Interval>& intervals) { if (intervals.empty()) return 0; sort(intervals.begin(), intervals.end(), [](Interval& a, Interval& b){return a.start < b.start;}); int res = 0, n = intervals.size(), endLast = intervals[0].end; for (int i = 1; i < n; ++i) { int t = endLast > intervals[i].start ? 1 : 0; endLast = t == 1 ? min(endLast, intervals[i].end) : intervals[i].end; res += t; } return res; } };
類似題目:
參考資料: