image.png

思路

image.png image.png

code

  1. class Solution {
  2. public int eraseOverlapIntervals(int[][] intervals) {
  3. if(intervals.length==0)
  4. return 0;
  5. Arrays.sort(intervals, new Comparator<int[]>() {
  6. @Override
  7. public int compare(int[] o1, int[] o2) {
  8. if (o1[1] != o2[1])
  9. return o1[1] - o2[1];
  10. return o1[0] - o2[0];
  11. }
  12. });
  13. //memo[i]表示intervals[0,,,i]区间能构成的最长不重叠区间序列
  14. int[] memo = new int[intervals.length];
  15. Arrays.fill(memo,1);
  16. for(int i =1;i<intervals.length;i++)
  17. for(int j=0;j<i;j++)
  18. if (intervals[i][0]>=intervals[j][1])
  19. memo[i] = Math.max(memo[i],1+memo[j]);
  20. int res = 0;
  21. for(int i:memo)
  22. res = Math.max(res,i);
  23. return intervals.length-res;
  24. }
  25. }

贪心

image.pngimage.png

  1. public int eraseOverlapIntervals(int[][] intervals) {
  2. if(intervals.length==0)
  3. return 0;
  4. Arrays.sort(intervals, new Comparator<int[]>() {
  5. @Override
  6. public int compare(int[] o1, int[] o2) {
  7. if(o1[1]!=o2[1])
  8. return o1[1]-o2[1];
  9. return o1[0]-o2[0];
  10. }
  11. });
  12. int res = 1;
  13. int pre = 0;
  14. for(int i =1;i<intervals.length;i++)
  15. if(intervals[i][0]>=intervals[pre][1]){
  16. res++;
  17. pre=i;
  18. }
  19. return intervals.length-res;
  20. }