leetcode 452. Minimum Number of Arrows to Burst Balloons 用最少数量的箭引爆气球(中等)
一、题目大意
标签: 贪心
https://leetcode.cn/problems/minimum-number-of-arrows-to-burst-balloons
有一些球形气球贴在一堵用 XY 平面表示的墙面上。墙面上的气球记录在整数数组 points ,其中points[i] = [xstart, xend] 表示水平直径在 xstart 和 xend之间的气球。你不知道气球的确切 y 坐标。
一支弓箭可以沿着 x 轴从不同点 完全垂直 地射出。在坐标 x 处射出一支箭,若有一个气球的直径的开始和结束坐标为 xstart,xend, 且满足 xstart ≤ x ≤ xend,则该气球会被 引爆 。可以射出的弓箭的数量 没有限制 。 弓箭一旦被射出之后,可以无限地前进。
给你一个数组 points ,返回引爆所有气球所必须射出的 最小 弓箭数 。
示例 1:
输入:points = [[10,16],[2,8],[1,6],[7,12]]
输出:2
解释:气球可以用2支箭来爆破:
-在x = 6处射出箭,击破气球[2,8]和[1,6]。
-在x = 11处发射箭,击破气球[10,16]和[7,12]。
示例 2:
输入:points = [[1,2],[3,4],[5,6],[7,8]]
输出:4
解释:每个气球需要射出一支箭,总共需要4支箭。
示例 3:
输入:points = [[1,2],[2,3],[3,4],[4,5]]
输出:2
解释:气球可以用2支箭来爆破:
- 在x = 2处发射箭,击破气球[1,2]和[2,3]。
- 在x = 4处射出箭,击破气球[3,4]和[4,5]。
提示:
- 1 <= points.length <= 105
- points[i].length == 2
- -231 <= xstart < xend <= 231 - 1
二、解题思路
区间重叠问题,一般都要想到贪心(局部最优等于全局最优)。本题给我们一堆大小不等的气球,用区间范围来表示气球大小,可能会有重叠区间,我们用最少的箭打爆所有气球。我们把所有区间按照右边界进行排序,因为每个气球都要被打破,因此排序得到的第一组数据我们一定要使用。只要沿着该数据最右边界的位置进行射箭一定能打破尽可能多的气球。然后依次移动射箭的位置,进行统计即可。
三、解题方法
3.1 Java实现
public class Solution {
public int findMinArrowShots(int[][] points) {
// 二维数组的排序??
Arrays.sort(points, Comparator.comparingInt(o -> o[1]));
int res = 1;
int end = points[0][1];
for (int i = 1; i < points.length; i++) {
if (points[i][0] <= end) {
end = Math.min(end, points[i][1]);
} else {
res++;
end = points[i][1];
}
}
return res;
}
}
四、总结小记
- 2022/7/27 恢复每日一题
相关文章
- 启动简单的springboot项目报错:To display the conditions report re-run your..Web server failed to start
- [LeetCode]709. 转换成小写字母
- 【LeetCode】114. Flatten Binary Tree to Linked List
- [LeetCode] 1309. Decrypt String from Alphabet to Integer Mapping 解码字母到整数映射
- [LeetCode] 1247. Minimum Swaps to Make Strings Equal 交换字符使得字符串相同
- [LeetCode] 1128. Number of Equivalent Domino Pairs 等价多米诺骨牌对的数量
- [LeetCode] 1022. Sum of Root To Leaf Binary Numbers 从根结点到叶结点的二进制数之和
- [LeetCode] 989. Add to Array-Form of Integer 数组形式的整数加法
- [LeetCode] To Lower Case 转为小写
- [LeetCode] All Paths From Source to Target 从起点到目标点到所有路径
- [LeetCode] Transform to Chessboard 转为棋盘
- [LeetCode] 774. Minimize Max Distance to Gas Station 最小化去加油站的最大距离
- [LeetCode] Best Time to Buy and Sell Stock with Transaction Fee 买股票的最佳时间含交易费
- [LeetCode] 568. Maximum Vacation Days 最大化休假日
- [LeetCode] Best Time to Buy and Sell Stock with Cooldown 买股票的最佳时间含冷冻期
- [LeetCode] Partition List 划分链表
- [LeetCode] 12. Integer to Roman 整数转化成罗马数字
- leetcode 121 Best Time to Buy and Sell Stock 买卖股票的最佳时机(简单)