package com.example.lettcode.dailyexercises;
import java.util.Arrays;
import java.util.Comparator;
/**
* @Class EraseOverlapIntervals
* @Description 435 无重叠区间
* 给定一个区间的集合,找到需要移除区间的最小数量,使剩余区间互不重叠。
* 注意:
* 可以认为区间的终点总是大于它的起点。
* 区间 [1,2] 和 [2,3] 的边界相互“接触”,但没有相互重叠。
* <p>
* 示例 1:
* 输入: [ [1,2], [2,3], [3,4], [1,3] ]
* 输出: 1
* 解释: 移除 [1,3] 后,剩下的区间没有重叠。
* <p>
* 示例 2:
* 输入: [ [1,2], [1,2], [1,2] ]
* 输出: 2
* 解释: 你需要移除两个 [1,2] 来使剩下的区间没有重叠。
* <p>
* 示例 3:
* 输入: [ [1,2], [2,3] ]
* 输出: 0
* <p>
* 解释: 你不需要移除任何区间,因为它们已经是无重叠的了。
* @Author
* @Date 2020/12/31
**/
public class EraseOverlapIntervals {
}
/**
* 方法一:贪心算法
*
* @param intervals
* @return
*/
public static int eraseOverlapIntervalsGreedy(int[][] intervals) {
if (intervals == null || intervals.length <= 1) return 0;
Arrays.sort(intervals, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return o1[0] - o2[0];
}
});
int res = 0;
int prev = 0;
for (int i = 1; i < intervals.length; i++) {
if (intervals[prev][1] > intervals[i][0]) { // 判断是否有重叠
if (intervals[prev][1] > intervals[i][1]) { // i 被 prev 包围,将i作为新的prev
prev = i; // 否则将i作为去除的重叠区间,因为这样留给的后面的空间更大
}
res++;
} else {
prev = i;
}
}
return res;
}
/**
* 方法二:动态规划
*
* @param intervals
* @return
*/
public static int eraseOverlapIntervalsBP(int[][] intervals) {
if (intervals == null || intervals.length <= 1) return 0;
Arrays.sort(intervals, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return o1[0] - o2[0];
}
});
// 以i元素为结尾,前i个元素最大不重叠区间数
int[] dp = new int[intervals.length];
int maxNotOverlap = 1;
for (int i = 0; i < intervals.length; i++) {
dp[i] = 1;
for (int j = i - 1; j >= 0; j--) {
// 无重叠
if (intervals[i][0] >= intervals[j][1]) {
dp[i] = Math.max(dp[i], dp[j] + 1);
}
}
maxNotOverlap = Math.max(maxNotOverlap, dp[i]);
}
return dp.length - maxNotOverlap;
}
// 测试用例
public static void main(String[] args) {
int[][] intervals = new int[][]{{1, 2}, {2, 3}, {3, 4}, {1, 3}};
int ans = eraseOverlapIntervals(intervals);
System.out.println("EraseOverlapIntervals demo01 result:" + ans);
intervals = new int[][]{{1, 2}, {1, 2}, {1, 2}};
ans = eraseOverlapIntervals(intervals);
System.out.println("EraseOverlapIntervals demo02 result:" + ans);
intervals = new int[][]{{1, 2}, {2, 3}};
ans = eraseOverlapIntervals(intervals);
System.out.println("EraseOverlapIntervals demo03 result:" + ans);
}