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

解题思路

这道题的解决思路其实就是找重叠区间最多的位置x的数量。此题采用贪心算法求解。算法共三步:

1、将存储气球位置的points数组按照每个气球的起始点的位置进行排序,便于后续操作。这里使用系统内置的sort函数。

2、设定初始可以放置箭矢发射的位置空间为0号气球的位置(排序后的points数组的0号元素points[0]),放置箭矢发射的位置空间的右边界用变量 end 记录。

3、假如第x个气球的左边界小于当前记录的 end 值,说明当前放置的箭矢可以射爆第x个气球,箭矢的数量不需要增加。但要注意,第x个气球的右边界可能小于当前记录的 end 值,此时需要将当前的重叠区域的右边界更新为第x个气球的右边界。否则,假如第x个气球的左边界已经大于当前记录的 end 值,那说明这个气球不能被射爆,要使用新的箭矢。箭矢的数量要加1,同时将 end 值更新为第x个气球的右边界。重复上述步骤直到遍历完所有气球。

注:由于points数组已经按照每个气球的左边界进行了排序,因此后面的算法过程不再需要记录气球的左边界的位置,因为从位置 end 射出的箭矢一定能射爆重叠区域的所有气球。

C++代码

class Solution {
public:
    int findMinArrowShots(vector<pair<int, int>>& points) {
        if(points.empty()) return 0;
        
        sort(points.begin(), points.end(), [](const pair<int, int> a, const pair<int, int> b){ return a.first < b.first; });
        
        int arrows = 1;
        int end = points[0].second;
        
        for(int i = 1; i < points.size(); i++) {
            if(points[i].first <= end) {
                if(end >= points[i].second)
                    end = points[i].second;
            }
            else {
                arrows++;
                end = points[i].second;
            }
        }
        return arrows;
    }
};

你可能感兴趣的:(LeetCode题解)