原题链接在这里:https://leetcode.com/problems/non-overlapping-intervals/description/
题目:
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.
题解:
可以采用DP, 保存到当前点能保留最多段不overlap的个数.
先把intervals按照interval的end排序.
对于第 i 段, 找到前面最后碰到的 j 使intervals[j].end < intervals[i].start. 那么dp[j]+1 就是包含第 i 段. dp[i-1]就是不包含第 i 段.
维护全局最大值, 最后用intervals.length减掉这个最大值就是最少去掉的interval数目.
Time Complexity: O(n^2). n = intervals.length.
Space: O(n).
AC Java:
1 /** 2 * Definition for an interval. 3 * public class Interval { 4 * int start; 5 * int end; 6 * Interval() { start = 0; end = 0; } 7 * Interval(int s, int e) { start = s; end = e; } 8 * } 9 */ 10 class Solution { 11 public int eraseOverlapIntervals(Interval[] intervals) { 12 if(intervals == null || intervals.length == 0){ 13 return 0; 14 } 15 16 int res = 1; 17 Arrays.sort(intervals, new Comparator<Interval>(){ 18 public int compare(Interval i1, Interval i2){ 19 return i1.end-i2.end; 20 } 21 }); 22 23 int [] dp = new int[intervals.length]; 24 dp[0] = 1; 25 for(int i = 1; i<intervals.length; i++){ 26 int max = 1; 27 for(int j = i-1; j>=0; j--){ 28 if(intervals[j].end <= intervals[i].start){ 29 max = Math.max(max, dp[j]+1); 30 break; 31 } 32 } 33 34 // include intervals[i]就是max, exclude就是dp[i-1]. 35 dp[i] = Math.max(max, dp[i-1]); 36 res = Math.max(res, dp[i]); 37 } 38 39 return intervals.length-res; 40 } 41 }
使用Greedy, 按照end把intervals排序.
如果出现overlap时去掉后面的能尽可能留下空间给将来的interval. 自己画画图.
Time Complexity: O(nlogn). n = intervals.length.
Space: O(1).
AC Java:
1 /** 2 * Definition for an interval. 3 * public class Interval { 4 * int start; 5 * int end; 6 * Interval() { start = 0; end = 0; } 7 * Interval(int s, int e) { start = s; end = e; } 8 * } 9 */ 10 class Solution { 11 public int eraseOverlapIntervals(Interval[] intervals) { 12 if(intervals == null || intervals.length == 0){ 13 return 0; 14 } 15 16 Arrays.sort(intervals, new Comparator<Interval>(){ 17 public int compare(Interval i1, Interval i2){ 18 return i1.end - i2.end; 19 } 20 }); 21 22 int res = 1; 23 int lastEnd = intervals[0].end; 24 for(int i = 1; i<intervals.length; i++){ 25 if(lastEnd <= intervals[i].start){ 26 res++; 27 lastEnd = intervals[i].end; 28 } 29 } 30 31 return intervals.length-res; 32 } 33 }