1. 程式人生 > >[LeetCode] Minimum Number of Arrows to Burst Balloons 最少數量的箭引爆氣球

[LeetCode] 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

Explanation:
One way is to shoot one arrow for example at x = 6 (bursting the balloons [2,8] and [1,6]) and another arrow at x = 11 (bursting the other two balloons).

這道題給了我們一堆大小不等的氣球,用區間範圍來表示氣球的大小,可能會有重疊區間。然後我們用最少的箭數來將所有的氣球打爆。那麼這道題是典型的用貪婪演算法來做的題,因為區域性最優解就等於全域性最優解,我們首先給區間排序,我們不用特意去寫排序比較函式,因為預設的對於pair的排序,就是按第一個數字升序排列,如果第一個數字相同,那麼按第二個數字升序排列,這個就是我們需要的順序,所以直接用即可。然後我們將res初始化為1,因為氣球數量不為0,所以怎麼也得先來一發啊,然後這一箭能覆蓋的最遠位置就是第一個氣球的結束點,用變數end來表示。然後我們開始遍歷剩下的氣球,如果當前氣球的開始點小於等於end,說明跟之前的氣球有重合,之前那一箭也可以照顧到當前的氣球,此時我們要更新end的位置,end更新為兩個氣球結束點之間較小的那個,這也是當前氣球和之前氣球的重合點,然後繼續看後面的氣球;如果某個氣球的起始點大於end了,說明前面的箭無法覆蓋到當前的氣球,那麼就得再來一發,既然又來了一發,那麼我們此時就要把end設為當前氣球的結束點了,這樣貪婪演算法遍歷結束後就能得到最少的箭數了,參見程式碼如下:

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

參考資料: