Leetcode 452. Minimum Number of Arrows to Burst Balloons
There are a number of spherical balloons spread in two-dimensional space. For each balloon, provided input is the start and end coordinates of the horizontal diameter. Since it’s horizontal, y-coordinates don’t matter and hence the x-coordinates of start and end of the diameter suffice. Start is always smaller than end. There will be at most 104 balloons.An arrow can be shot up exactly vertically from different points along the x-axis. A balloon with xstart and xend bursts by an arrow shot at x if xstart ≤ x ≤ xend. There is no limit to the number of arrows that can be shot. An arrow once shot keeps travelling up infinitely. The problem is to find the minimum number of arrows that must be shot to burst all balloons.
Example:
Input:
[[10,16], [2,8], [1,6], [7,12]]
Output:
2
题目大意:
给定一个数组其元素代表一堆大小不等的气球,用区间范围来表示气球的大小且可能会有重叠区间。求将所有的气球打爆的最少箭数。
解题思路:
典型的贪心策略,首先对数组从小到大排序,设置一个当前射飞镖的坐标值cur,我们的目的是将尽可能多的气球用这个飞镖一次射爆,每个气球集中的极限是它的右侧。遍历数组,当气球的右侧小于等于cur,则说明该气球可以用当前的飞镖射中,但需更新cur为该气球的右侧;当气球的左侧大于cur,则说明无法击中,需飞出一个飞镖并更新cur值为该气球的右侧。主要要将飞镖数初始为1,因为至少需要射一次。时间复杂度为O(nlogn).
代码:
class Solution {
public:
int findMinArrowShots(vector<vector<int>>& points) {
if(points.empty())
return 0;
sort(points.begin(), points.end());
int num = 1, cur = points[0][1];
for(int i = 1; i < points.size(); i++)
{
if(points[i][1] <= cur)
cur = points[i][1];
else if(points[i][0] > cur)
{
num++;
cur = points[i][1];
}
}
return num;
}
};
本文解析了LeetCode上编号为452的问题“Minimum Number of Arrows to Burst Balloons”,这是一个关于计算最少箭数以射爆所有气球的算法挑战。文章介绍了问题背景,给出了一个贪心策略的解决方案,并详细解释了实现过程。通过将气球按位置排序并跟踪箭头可以射中的最远点,算法能够有效地确定最少的射击次数。

被折叠的 条评论
为什么被折叠?



