LeetCode435, non-overlapping interval (greedy selection interval scheduling)

Title description

https://leetcode-cn.com/problems/non-overlapping-intervals/
Insert picture description here

solution

Greedy selection is suitable for solving the problem of cross-activity, and the scope of use is very small. For this question, our greedy choice is: each time we choose the activity with the earliest end time that does not cross from the remaining activities. All crosses are eliminated.

class Solution {
    
    
    public int eraseOverlapIntervals(int[][] intervals) {
    
    
        //使用贪心算法里面的区间调度问题,每次选择当前活动集合里面结束时间最早的加入所选集合
        //返回不选的集合元素个数
        if(intervals==null || intervals.length==0) return 0;
        //1、对活动的end时间进行升序排序
        Arrays.sort(intervals,new Comparator<int[]>(){
    
    
            public int compare(int[]a,int[]b){
    
    
                return a[1]>b[1]?1:-1;//升序排序
            }
        });
        //贪心选择
        int count = 1;//必须
        int end = intervals[0][1];//第一个活动就是加入的
        for(int i=1;i<intervals.length;i++){
    
    
            int start = intervals[i][0];//当前活动的时间比end小才可以
            if(end<=start){
    
    
                end = intervals[i][1];//更新
                count++;
            }
        }
        return intervals.length-count;

    }
}

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_44861675/article/details/114579237