452. Minimum Number of Arrows to Burst Balloons

There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array points where pointsi = xstart, xend denotes a balloon whose horizontal diameter stretches between xstart and xend. You do not know the exact y-coordinates of the balloons.

Arrows can be shot up directly vertically (in the positive y-direction) from different points along the x-axis. A balloon with xstart and xend is burst by an arrow shot at x if xstart <= x <= xend. There is no limit to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path.

Given the array points, return the minimum number of arrows that must be shot to burst all balloons.

Example 1:

Input: points = \[10,16,2,8,1,6,7,12]

Output: 2

Explanation: The balloons can be burst by 2 arrows:

  • Shoot an arrow at x = 6, bursting the balloons 2,8 and 1,6.
  • Shoot an arrow at x = 11, bursting the balloons 10,16 and 7,12.
    Example 2:

Input: points = \[1,2,3,4,5,6,7,8]

Output: 4

Explanation: One arrow needs to be shot for each balloon for a total of 4 arrows.

Example 3:

Input: points = \[1,2,2,3,3,4,4,5]

Output: 2

Explanation: The balloons can be burst by 2 arrows:

  • Shoot an arrow at x = 2, bursting the balloons 1,2 and 2,3.
  • Shoot an arrow at x = 4, bursting the balloons 3,4 and 4,5.

Constraints:

1 <= points.length <= 105

pointsi.length == 2

-231 <= xstart < xend <= 231 - 1

Approach

First, let's consider the following example:

Input: points = \[10,12,2,8,1,6,7,12].

It is clear that the balloons can be burst by 2 arrows. The first arrow can be shot within the range of 2 to 6.

For instance, shooting an arrow at x = 6 will burst the balloons 2,8 and 1,6.

The last arrow can be shot within the range of 10 to 12.

For example, shooting an arrow at x = 11 will burst the balloons 10,16 and 7,12.

However, it can be challenging to write the code by given array in a specific order.

To write code efficiently, sort the points by their start index (the first index of the coordinates).

For instance, the initial balloon is located at 1,6.

To burst this balloon, the arrow must be shot within a range of 1 to 6. Then, we encounter another balloon. Since we have sorted the points beforehand, we can determine if the balloons overlap by comparing the second balloon's start and the first balloon's end (6 > 2).

To burst two overlapping balloons with coordinates 1,6 and 2,8, only one arrow is needed with a range of 2,6. However, the third balloon cannot be reached by the first arrow, which has a range of 2,6, so another arrow is required. Following the same analysis as before, a second arrow with a range of 10,12 can burst the balloons 10,16 and 7,12.

code

cpp 复制代码
bool compare(vector<int> &a, vector<int> &b);
class Solution {
public:
    int findMinArrowShots(vector<vector<int>>& points) {
        sort(points.begin() , points.end() ,compare );
        int arrowEnd = points[0][1];
        int minNum =1;

        for(int i=0;i<points.size();i++)
        {
            if(arrowEnd>=points[i][0] )
            {
                arrowEnd = min(points[i][1] , arrowEnd);
            }
            else
            {
                minNum++;
                arrowEnd=points[i][1];
            }
        }
        return minNum;
    }
};

bool compare(vector<int> &a, vector<int> &b)
{
    if(a[0] != b[0])
    {
        return a[0]<b[0];
    }
    return a[1]<b[1];
}

leetcode 452. Minimum Number of Arrows to Burst Balloons

https://www.youtube.com/watch?v=_WIFehFkkig

英语参考

Idea:

We know that eventually we have to shoot down every balloon, so for each ballon there must be an arrow whose position is between balloon0 and balloon1 inclusively. Given that, we can sort the array of balloons by their ending position. Then we make sure that while we take care of each balloon in order, we can shoot as many following balloons as possible.

So what position should we pick each time? We should shoot as to the right as possible, because since balloons are sorted, this gives you the best chance to take down more balloons. Therefore the position should always be ballooni1 for the ith balloon.

This is exactly what I do in the for loop: check how many balloons I can shoot down with one shot aiming at the ending position of the current balloon. Then I skip all these balloons and start again from the next one (or the leftmost remaining one) that needs another arrow.

Example:

balloons = \[7,10, 1,5, 3,6, 2,4, 1,4]

After sorting, it becomes:

balloons = \[2,4, 1,4, 1,5, 3,6, 7,10]

So first of all, we shoot at position 4, we go through the array and see that all first 4 balloons can be taken care of by this single shot. Then we need another shot for one last balloon. So the result should be 2.

Code:

public int findMinArrowShots(int\[\]\[\] points) {

if (points.length == 0) {

return 0;

}

Arrays.sort(points, (a, b) -> a1 - b1);

int arrowPos = points01;

int arrowCnt = 1;

for (int i = 1; i < points.length; i++) {

if (arrowPos >= pointsi0) {

continue;

}

arrowCnt++;

arrowPos = pointsi1;

}

return arrowCnt;

}

Here I provide a concise template that I summarize for the so-called "Overlapping Interval Problem", e.g. Minimum Number of Arrows to Burst Balloons, and Non-overlapping Intervals etc. I found these problems share some similarities on their solutions.

Sort intervals/pairs in increasing order of the start position.

Scan the sorted intervals, and maintain an "active set" for overlapping intervals. At most times, we do not need to use an explicit set to store them. Instead, we just need to maintain several key parameters, e.g. the number of overlapping intervals (count), the minimum ending point among all overlapping intervals (minEnd).

If the interval that we are currently checking overlaps with the active set, which can be characterized by cur.start > minEnd, we need to renew those key parameters or change some states.

If the current interval does not overlap with the active set, we just drop current active set, record some parameters, and create a new active set that contains the current interval.

int count = 0; // Global parameters that are useful for results.

int minEnd = INT_MAX; // Key parameters characterizing the "active set" for overlapping intervals, e.g. the minimum ending point among all overlapping intervals.

sort(points.begin(), points.end()); // Sorting the intervals/pairs in ascending order of its starting point

for each interval {

if(interval.start > minEnd) { // If the

// changing some states, record some information, and start a new active set.

count++;

minEnd = p.second;

}

else {

// renew key parameters of the active set

minEnd = min(minEnd, p.second);

}

}

return the result recorded in or calculated from the global information;

For example, for the problem Minimum "Number of Arrows to Burst Balloons", we have

Sort balloons in increasing order of the start position.

Scan the sorted pairs, and maintain a pointer for the minimum end position for current "active balloons", whose diameters are overlapping.

When the next balloon starts after all active balloons, shoot an arrow to burst all active balloons, and start to record next active balloons.

int findMinArrowShots(vector<pair<int, int>>& points) {

int count = 0, minEnd = INT_MAX;

sort(points.begin(), points.end());

for(auto& p: points) {

if(p.first > minEnd) {count++; minEnd = p.second;}

else minEnd = min(minEnd, p.second);

}

return count + !points.empty();

}

For the problem "Non-overlapping Intervals", we have

int eraseOverlapIntervals(vector& intervals) {

int total = 0, minEnd = INT_MIN, overNb = 1;

sort(intervals.begin(), intervals.end(), \&(Interval& inter1, Interval& inter2) {return inter1.start < inter2.start;});

for(auto& p: intervals) {

if(p.start >= minEnd) {

total += overNb-1;

overNb = 1;

minEnd = p.end;

}

else {

overNb++;

minEnd = min(minEnd, p.end);

}

}

return total + overNb-1;

}

To facilitate identifying coincidence in a single traversal, we sort in ascending order on the right

相关推荐
CC数学建模9 分钟前
2026第八届中青杯全国大学生数学建模竞赛C题:情绪维度耦合约束的脑电信号情绪识别 (1)完整思路、代码、模型、文章,全网首发高质量分享!
python·算法·数学建模
Dillon Dong11 分钟前
【风电控制】双馈风机网侧高低穿控制策略——从VrtCal信号处理到状态机逻辑的完整解析
算法·变流器·风电控制·dfig
下午写HelloWorld12 分钟前
同态加密(Homomorphic Encryption, HE)
人工智能·算法·密码学·同态加密
CC数学建模12 分钟前
2026第八届中青杯全国大学生数学建模竞赛B题:AI生成内容的质量评估与参数优化完整思路、代码、模型、文章,全网首发高质量分享!
python·算法·数学建模
sheeta199813 分钟前
LeetCode 每日一题笔记 日期:2026.06.04 题目:3751. 范围内总波动值 I
笔记·算法·leetcode
lightqjx24 分钟前
【算法】数据结构_单调栈
数据结构·算法·单调栈
Promise微笑26 分钟前
洞察无形:红外热像仪应用场景与高性价比之选
人工智能·物联网·算法
8Qi831 分钟前
LeetCode 746:使用最小花费爬楼梯 —— 题解笔记
java·笔记·算法·leetcode·动态规划
pipo34 分钟前
没雷达也能调 Nav2?我开源了一套仿真到实机复用的 ROS 2 3D LiDAR 导航工作空间
算法
计算机安禾41 分钟前
【算法分析与设计】第44篇:随机化复杂度类:RP、BPP与去随机化猜想
java·数据结构·数据库·算法·机器学习