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;
    }
}
相关推荐
蚰蜒螟几秒前
Netty 的 Select/Poll 机制核心实现主要在 NioEventLoop 的事件循环
java·开发语言
_不会dp不改名_1 分钟前
leetcode_42 接雨水
算法·leetcode·职场和发展
Swaggy T2 分钟前
自动驾驶轨迹规划算法——Apollo EM Planner
人工智能·算法·自动驾驶
野生的编程萌新32 分钟前
从冒泡到快速排序:探索经典排序算法的奥秘(二)
c语言·开发语言·数据结构·c++·算法·排序算法
Full Stack Developme33 分钟前
Java后台生成多个Excel并用Zip打包下载
java·开发语言·excel
iLoyalty34 分钟前
防御保护15
算法·哈希算法
Brookty35 分钟前
【Java学习】锁、线程死锁、线程安全2
java·开发语言·学习·java-ee
weixin_307779131 小时前
VS Code配置MinGW64编译backward库
开发语言·c++·vscode·算法
百锦再1 小时前
.NET 的 WebApi 项目必要可配置项都有哪些?
java·开发语言·c#·.net·core·net
耳东哇1 小时前
spring ai-openai-vl模型应用qwen-vl\gpt-文字识别-java
java·人工智能·spring