題目要求
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.
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:
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.
使用二維數組表示區間組,每一個子數組的第一個值表示區間的開始座標,第二個值表示區間的結束座標。計算最少進行多少次刪除操作,可以確保剩下的區間不會產生任何重疊。
思路和代碼
假設有兩個區間, 這兩個區間之間會存在以下幾種關係:
- 毫無重疊,此時無需進行刪除
- 部分重疊。則需要找出和周圍區間交叉最少的區間進行保留。如果將區間按照從小到大的次序排列,出現這種情況時,每次都保留前一個區間。
- 區間1爲區間2的子區間或區間2爲區間1的子區間,則保留子區間,刪除父區間
代碼如下:
public int eraseOverlapIntervals(int[][] intervals) {
if(intervals == null || intervals.length == 0) return 0;
Arrays.sort(intervals, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
// TODO Auto-generated method stub
return o1[0] - o2[0] == 0 ? o1[1] - o2[1] : o1[0] - o2[0];
}
});
int count = 0;
int end = intervals[0][1];
for(int i = 1 ; i<intervals.length ; i++) {
int[] interval = intervals[i];
if(interval[0] < end) {;
count++;
end = Math.min(end, interval[1]);
}else {
end = interval[1];
}
}
return count;
}