leetcode:(435) Non-overlapping Intervals(java)
阿新 • • 發佈:2018-12-02
題目:
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.
題目描述:
給定一個區間陣列,計算其中區間重疊陣列的數量。
解題思路:
將陣列按照區間尾值大小進行排序,然後找出最多能組成區間不重疊陣列的數量,用總的區間個數減去最多區間不重疊陣列的數量即為所求的區間重疊陣列數量。具體思路及程式碼如下:
import java.util.Arrays;
import java.util.Comparator;
public class GreedyThought_EraseOverLapIntervals_435_1108 {
public int eraseOverLapIntervals(Interval[] intervals) {
//判空
if (intervals == null || intervals.length == 0) {
return 0;
}
//將區間按照區間末尾的值進行升序排序
Arrays.sort(intervals, Comparator.comparingInt(o -> o.end));
int end = intervals[0].end;
int count = 1; //第一個區間計入不重複區間
for (int i = 1; i < intervals.length; i++) {
if (intervals[i].start < end) {
continue;
}
end=intervals[i].end;
count++;
}
//區間的總個數減去不重複區間的個數即為所求個數
return intervals.length - count;
}
}