[LeetCode] 435. 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.

NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.

 

這道題給了我們一堆區間,讓求需要至少移除多少個區間才能使剩下的區間沒有重疊,那么首先要給區間排序,根據每個區間的 start 來做升序排序,然后開始要查找重疊區間,判斷方法是看如果前一個區間的 end 大於后一個區間的 start,那么一定是重復區間,此時結果 res 自增1,我們需要刪除一個,那么此時究竟該刪哪一個呢,為了保證總體去掉的區間數最小,我們去掉那個 end 值較大的區間,而在代碼中,我們並沒有真正的刪掉某一個區間,而是用一個變量 last 指向上一個需要比較的區間,我們將 last 指向 end 值較小的那個區間;如果兩個區間沒有重疊,那么此時 last 指向當前區間,繼續進行下一次遍歷,參見代碼如下:

 

解法一:

class Solution {
public:
    int eraseOverlapIntervals(vector<vector<int>>& intervals) {
        int res = 0, n = intervals.size(), last = 0;
        sort(intervals.begin(), intervals.end());
        for (int i = 1; i < n; ++i) {
            if (intervals[i][0] < intervals[last][1]) {
                ++res;
                if (intervals[i][1] < intervals[last][1]) last = i;
            } else {
                last = i;
            }
        }
        return res;
    }
};

 

我們也可以對上面代碼進行簡化,主要利用三元操作符來代替 if 從句,參見代碼如下: 

 

解法二:

class Solution {
public:
    int eraseOverlapIntervals(vector<vector<int>>& intervals) {
        if (intervals.empty()) return 0;      
        sort(intervals.begin(), intervals.end());
        int res = 0, n = intervals.size(), endLast = intervals[0][1];
        for (int i = 1; i < n; ++i) {
            int t = endLast > intervals[i][0] ? 1 : 0;
            endLast = t == 1 ? min(endLast, intervals[i][1]) : intervals[i][1];
            res += t;
        }
        return res;
    }
};

 

Github 同步地址:

https://github.com/grandyang/leetcode/issues/435

 

類似題目:

Find Right Interval

Data Stream as Disjoint Intervals 

Insert Interval

Merge Intervals

Maximum Length of Pair Chain

Minimum Number of Arrows to Burst Balloons 

 

參考資料:

https://leetcode.com/problems/non-overlapping-intervals/

https://leetcode.com/problems/non-overlapping-intervals/discuss/91713/Java%3A-Least-is-Most

https://leetcode.com/problems/non-overlapping-intervals/discuss/91700/Concise-C%2B%2B-Solution

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM