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;
    }
}
相关推荐
mit6.82427 分钟前
bfs|栈
算法
Y***h1871 小时前
第二章 Spring中的Bean
java·后端·spring
8***29311 小时前
解决 Tomcat 跨域问题 - Tomcat 配置静态文件和 Java Web 服务(Spring MVC Springboot)同时允许跨域
java·前端·spring
CoderYanger2 小时前
优选算法-栈:67.基本计算器Ⅱ
java·开发语言·算法·leetcode·职场和发展·1024程序员节
jllllyuz2 小时前
Matlab实现基于Matrix Pencil算法实现声源信号角度和时间估计
开发语言·算法·matlab
q***06292 小时前
Tomcat的升级
java·tomcat
夏鹏今天学习了吗2 小时前
【LeetCode热题100(72/100)】前 K 个高频元素
leetcode
稚辉君.MCA_P8_Java2 小时前
DeepSeek 插入排序
linux·后端·算法·架构·排序算法
多多*2 小时前
Java复习 操作系统原理 计算机网络相关 2025年11月23日
java·开发语言·网络·算法·spring·microsoft·maven
青云交2 小时前
Java 大视界 -- Java 大数据在智能物流无人配送车路径规划与协同调度中的应用
java·spark·路径规划·大数据分析·智能物流·无人配送车·协同调度