435. Non-overlapping Intervals[medium]

435. Non-overlapping Intervals-Interval Problem

Title description

Given a set of intervals, find the minimum number of intervals that need to be removed so that the remaining intervals do not overlap each other.

note:

可以认为区间的终点总是大于它的起点。
区间 [1,2] 和 [2,3] 的边界相互“接触”,但没有相互重叠。

Example 1:

输入: [ [1,2], [2,3], [3,4], [1,3] ]

输出: 1

解释: 移除 [1,3] 后,剩下的区间没有重叠。

Example 2:

输入: [ [1,2], [1,2], [1,2] ]

输出: 2

解释: 你需要移除两个 [1,2] 来使剩下的区间没有重叠。

Example 3:

输入: [ [1,2], [2,3] ]

输出: 0

解释: 你不需要移除任何区间,因为它们已经是无重叠的了。

answer

This question is also a way to solve the greedy problem and delete the least interval.

  • Require as few deletion intervals as possible
  • First sort the interval according to the end of the interval
  • Sub-problem: only need to ensure that the left end of each new interval >= the right end of the current reserved interval.

The comparator can refer to this

Code

class Solution {
    
    
    public int eraseOverlapIntervals(int[][] intervals) {
    
    
        //贪心问题:找到移除区间的最小数量
        // 意味着区间本身长度尽可能小
        // 子问题:优先保留结尾尽可能小 且不冲突的区间

        // 代码优化
        if(intervals.length == 0){
    
    
            return 0;
        }
        // 重构排序 比较器
        Arrays.sort(intervals,new Comparator<int []>(){
    
    
            public int compare(int[] interval1,int[] interval2){
    
    
                //比较区间末尾
                return interval1[1] -interval2[1];
            }
        });
        // 获取数组长度
        int n = intervals.length;
        // 设置第一个区间的末尾为初始值
        int right = intervals[0][1];
        // 第一个区间必然满足
        int ans = 1;
        for(int i=1; i<n; i++){
    
    
            //如果接下来的区间初始值比上一个末尾大,就可
            if(intervals[i][0] >= right){
    
    
                ++ans;
                right = intervals[i][1];

            }
        }
    return n-ans;
    }
}

Guess you like

Origin blog.csdn.net/qq_37747189/article/details/115095294