LeetCode 452. 用最少数量的箭引爆气球 java题解

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

java 复制代码
class Solution {
    public int findMinArrowShots(int[][] points) {
        //按区间起点排序
        Arrays.sort(points,new Comparator<int[]>(){
            public int compare(int[] a,int[] b){
                return a[0]-b[0];
            }
        });
        int len=points.length;
        if(len==1) return 1;
        int[] before=points[0];//第一个区间
        int count=1;
        for(int i=1;i<len;i++){
            //如果区间重叠
            if(points[i][0]>=before[0]&&points[i][0]<=before[1]){
                int[] cur=new int[2];
                cur[0]=Math.max(points[i][0],before[0]);
                cur[1]=Math.min(points[i][1],before[1]);
                before=cur;
            }
            else{//区间不重叠
                count++;//需要加一支箭
                before=points[i];
            }
        }
        return count;
    }
}
/**
ab两个区间有重叠的部分,ab两个区间合并后就只剩下重叠的部分。
 */

更简洁的别人的写法

java 复制代码
/**
 * 时间复杂度 : O(NlogN)  排序需要 O(NlogN) 的复杂度
 * 空间复杂度 : O(logN) java所使用的内置函数用的是快速排序需要 logN 的空间
 */
class Solution {
    public int findMinArrowShots(int[][] points) {
        // 根据气球直径的开始坐标从小到大排序
        // 使用Integer内置比较方法,不会溢出
        Arrays.sort(points, (a, b) -> Integer.compare(a[0], b[0]));

        int count = 1;  // points 不为空至少需要一支箭
        for (int i = 1; i < points.length; i++) {
            if (points[i][0] > points[i - 1][1]) {  // 气球i和气球i-1不挨着,注意这里不是>=
                count++; // 需要一支箭
            } else {  // 气球i和气球i-1挨着
                points[i][1] = Math.min(points[i][1], points[i - 1][1]); // 更新重叠气球最小右边界
            }
        }
        return count;
    }
}
相关推荐
尘觉37 分钟前
中秋节与 Spring Boot 的思考:一场开箱即用的团圆盛宴
java·spring boot·后端
逻辑留白陈42 分钟前
Adaboost进阶:与主流集成算法对比+工业级案例+未来方向
算法
Learn Beyond Limits1 小时前
Mean Normalization|均值归一化
人工智能·神经网络·算法·机器学习·均值算法·ai·吴恩达
天选之女wow1 小时前
【代码随想录算法训练营——Day28】贪心算法——134.加油站、135.分发糖果、860.柠檬水找零、406.根据身高重建队列
算法·leetcode·贪心算法
Gohldg1 小时前
C++算法·贪心例题讲解
c++·数学·算法·贪心算法
Le1Yu1 小时前
2025-10-7学习笔记
java·笔记·学习
popoxf1 小时前
spring容器启动流程(反射视角)
java·后端·spring
远远远远子2 小时前
类与对象 --1
开发语言·c++·算法
Aaplloo2 小时前
【无标题】
人工智能·算法·机器学习
西望云天2 小时前
The 2024 ICPC Asia Nanjing Regional Contest(2024南京区域赛EJKBG)
数据结构·算法·icpc