LeetCode452, use the least number of arrows to detonate the balloon (greedy selection interval scheduling)

Title description

https://leetcode-cn.com/problems/minimum-number-of-arrows-to-burst-balloons/
Insert picture description here

solution

Same as the essence of the previous question.

class Solution {
    
    
    public int findMinArrowShots(int[][] points) {
    
    
        //贪心选择,尽可能地一次射爆交叠最多的气球的坐标范围
        //剩余不交叠的区间,一支射爆一个

        //从可视化图上看,我们只需要求出最大不交叠的组合即可
        if(points==null || points.length==0) return 0;
        //1、对活动的end时间进行升序排序
        Arrays.sort(points,new Comparator<int[]>(){
    
    
            public int compare(int[]a,int[]b){
    
    
                return a[1]>b[1]?1:-1;//升序排序
            }
        });
        //贪心选择
        int count = 1;//必须
        int end = points[0][1];
        for(int i=1;i<points.length;i++){
    
    
            int start = points[i][0];
            if(end<start){
    
    //相等也是交叠
                end = points[i][1];//更新
                count++;
            }
        }
        return count;

    }
}

Insert picture description here

After reading the following questions and comments, a very interesting but serious question: When
Insert picture description here
sorting, don't write it like the following to save trouble. The data will overflow. Or honestly compare the size to return positive and negative.

 Arrays.sort(points,new Comparator<int[]>(){
    
    
            public int compare(int[]a,int[]b){
    
    
                //return a[1]>b[1]?1:-1;//升序排序
                return a[1]-b[1];
            }
        });

Guess you like

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