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.
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.
关键词: greedy, 2D array, sort
思路:
- 按照内嵌数组[1] 进行排序,因为这样能让范围更大的内嵌数组涵盖更多的数组,减少剔除重复区间的次数。
- 建一个flag作为区间指标,如果接下的数组有和flag重合,count++;否则更新flag。
解题:时间复杂度: O(nlogn);空间复杂度:O(1)
var eraseOverlapIntervals = function(intervals) {
if (!intervals || !intervals[0] || intervals.length == 0 || intervals[0].length == 0) return 0;
intervals.sort((n1, n2) => {
return n1[1] - n2[1]; //sort by [1] rather [0] can see larger range will overlap, since we wanna remove minimum.
});
let count = 0;
let flag = [intervals[0][0], intervals[0][1]];
for (let i = 1; i < intervals.length; i++){
if (flag[1] > intervals[i][0]) { //already sorted, so only think [0]
count++;
}
else{//update flag
flag = [intervals[i][0], intervals[i][1]];
}
}
return count;
};