Stay Hungry,Stay Foolish!

452. 用最少数量的箭引爆气球

452. 用最少数量的箭引爆气球

 https://leetcode.cn/problems/minimum-number-of-arrows-to-burst-balloons/description/?envType=study-plan-v2&envId=top-interview-150
 

Code

class Solution {
public:
    int findMinArrowShots(vector<vector<int>>& points) {
        sort(points.begin(), points.end(), [](vector<int>&a, vector<int>&b){
            return a[1] < b[1];
        });

        /*
        now all points are ordered by endpoint of each point

        3           -------
        2     ----------  
        1       ------
        0    ------
        
        first we take the rightmost value of point 0 as benchmark to put stick
        for 1 and 2, their leftmost values are less than benchmark,
        so they can be caught by the stick
        for 3, its leftmost value is more than benchmark,
        so it cannot be caught by the stick
        then this stick is over for catch,
        we put stick at the position of rightmost value of 3 point, start next loop.
        */

        int rightmost = points[0][1];

        int ans = 1;
        for(int i=1; i<points.size(); i++){
            if (rightmost < points[i][0]){
                ans++;
                rightmost = points[i][1];
            }
        }

        return ans;
    }
};

 

 
posted @ 2024-03-30 09:20  lightsong  阅读(3)  评论(0编辑  收藏  举报
Life Is Short, We Need Ship To Travel