Algorithm/src/main/java/greedy/FindMinArrowShots.java
2025-04-09 12:50:45 +08:00

35 lines
1.5 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package greedy;
import java.util.Arrays;
import java.util.HashMap;
/**
* 题目: 452. 用最少数量的箭引爆气球 (findMinArrowShots)
* 描述:有一些球形气球贴在一堵用 XY 平面表示的墙面上。墙面上的气球记录在整数数组 points 其中points[i] = [xstart, xend] 表示水平直径在 xstart 和 xend之间的气球。你不知道气球的确切 y 坐标。
* 一支弓箭可以沿着 x 轴从不同点 完全垂直 地射出。在坐标 x 处射出一支箭,若有一个气球的直径的开始和结束坐标为 xstartxend 且满足 xstart ≤ x ≤ xend则该气球会被 引爆 。可以射出的弓箭的数量 没有限制 。 弓箭一旦被射出之后,可以无限地前进。
* 给你一个数组 points ,返回引爆所有气球所必须射出的 最小 弓箭数 。
示例 2
输入points = [[10,16],[2,8],[1,6],[7,12]]
输出2
解释气球可以用2支箭来爆破:
-在x = 6处射出箭击破气球[2,8]和[1,6]。
-在x = 11处发射箭击破气球[10,16]和[7,12]。
* 链接https://leetcode.cn/problems/minimum-number-of-arrows-to-burst-balloons/
*/
public class FindMinArrowShots {
public int findMinArrowShots(int[][] points) {
Arrays.sort(points, (a, b) -> Integer.compare(a[1], b[1]));
int index=0,cnt=0;
while(index<points.length){
int temp=index;
while(index<points.length&&points[temp][1]>=points[index][0])
index++;
cnt++;
}
return cnt;
}
}