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;
    }
}
相关推荐
程序猿乐锅16 分钟前
从0-1一文详解RabbitMQ
java·分布式·后端·中间件·rabbitmq·ruby
考虑考虑4 小时前
JDK26中的List.ofLazy()
java·后端·java ee
小蒜学长4 小时前
基于SpringBoot的公寓报修管理系统的设计与实现(代码+数据库+LW)
java·spring boot·后端·公寓报修管理系统·多角色协同
for_ever_love__4 小时前
MySQL 主从复制讲透:binlog 原理、搭建步骤与读写分离
java·数据库·mysql·binlog·读写分离·原理·主从复制
Nil2085 小时前
leetcode 118杨辉三角
算法·leetcode·职场和发展
小π军6 小时前
操作系统面试题
java·linux·服务器
倔强的石头1067 小时前
应用账号最小权限实践:读写账号、报表账号、运维账号分层
java·运维·开发语言
Shaoshing7 小时前
ThreadLocal
java·jvm·threadlocal
写后端的胖头鱼7 小时前
一文详解CAS
java·jvm·spring·cas·乐观锁·自旋