[LeetCode] 435. Non-overlapping Intervals

Given an array of intervals intervals where intervals[i] = [starti, endi], return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.

Example 1:

Input: intervals = [[1,2],[2,3],[3,4],[1,3]]
Output: 1
Explanation: [1,3] can be removed and the rest of the intervals are non-overlapping.

Example 2:

Input: intervals = [[1,2],[1,2],[1,2]]
Output: 2
Explanation: You need to remove two [1,2] to make the rest of the intervals non-overlapping.

Example 3:

Input: intervals = [[1,2],[2,3]]
Output: 0
Explanation: You don't need to remove any of the intervals since they're already non-overlapping.

Constraints:

  • 1 <= intervals.length <= 105
  • intervals[i].length == 2
  • -5 * 104 <= starti < endi <= 5 * 104

不重叠的区间。

给定一个区间的集合 intervals ,其中 intervals[i] = [starti, endi] 。返回 需要移除区间的最小数量,使剩余区间互不重叠 。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/non-overlapping-intervals
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路还是扫描线。既然是找是否有重叠,那么可以根据每个 interval 的结束时间对 input 进行排序。排序之后遍历 intervals,记录不重叠的 interval 一共有几个(记为count),然后用 intervals 的总长度 L - count 得到最后要的结果。跑个例子,

[[1,2],[2,3],[3,4],[1,3]]

按end排序之后的结果是

[ [ 1, 2 ], [ 2, 3 ], [ 1, 3 ], [ 3, 4 ] ]

之后从第二个 interval 开始遍历,如果当前 interval 的 start 大于等于前一个 interval 的 end,说明两者没有 overlap,则 count++,说明这两个 interval 都需要保留。按照这个逻辑,算出最后互不重叠的 intervals 有多少,再用 总数 - count 就得到需要去除的 interval 的数量了。

时间O(nlogn)

空间O(1)

JavaScript实现

 1 /**
 2  * @param {number[][]} intervals
 3  * @return {number}
 4  */
 5 var eraseOverlapIntervals = function(intervals) {
 6     // corner case
 7     if (intervals.length === 0) {
 8         return 0;
 9     }
10 
11     // normal case
12     intervals = intervals.sort((a, b) => a[1] - b[1]);
13     let end = intervals[0][1];
14     let count = 1;
15     for (let i = 1; i < intervals.length; i++) {
16         if (intervals[i][0] >= end) {
17             end = intervals[i][1];
18             count++;
19         }
20     }
21     return intervals.length - count;
22 };

 

Java实现

 1 class Solution {
 2     public int eraseOverlapIntervals(int[][] intervals) {
 3         // corner case
 4         if (intervals.length == 0) {
 5             return 0;
 6         }
 7 
 8         // normal case
 9         Arrays.sort(intervals, (a, b) -> a[1] - b[1]);
10         int end = intervals[0][1];
11         int count = 1;
12         for (int i = 1; i < intervals.length; i++) {
13             if (intervals[i][0] >= end) {
14                 end = intervals[i][1];
15                 count++;
16             }
17         }
18         return intervals.length - count;
19     }
20 }

 

扫描线相关题目

LeetCode 题目总结

posted @ 2019-11-01 12:16  CNoodle  阅读(239)  评论(0编辑  收藏  举报