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

题意:每一个气球在一个区间[s,e]内,从某一个点射出一支箭,可以将经过该点的气球引爆,问引爆所有气球至少需要多少只箭。

思路:按起始点将所有气球排序,引爆一只气球最佳的地点在这支气球的终点,记为cur_end,因为这样能够引爆更多的气球,当另外一只气球b的区间与引爆点重叠时,此时的最佳引爆点成了min(cur_end, b.end).如果该气球的区间不与此时的引爆点重叠时,这时需要另外开一个引爆点。

时间复杂度:O(N)

C++代码:

class Solution {

public:

    struct node{

        int s, e;

        node(int s, int e): s(s), e(e){}

        bool operator < (node a){

            return s < a.s;

        }

    };

    vector<node> bl;

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

        for(int i = 0; i < points.size(); i++){

            bl.push_back(node(points[i][0], points[i][1]));

        }

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

        int res = 0;

        bool start = false;

        int cur_end;

        for(int i = 0; i < points.size(); i++){

            if(start == false){

                cur_end = bl[i].e;

                res++;

            }else{

                if(cur_end > bl[i].e){

                    cur_end = bl[i].e;

                }

                else if (bl[i].s > cur_end){

                    cur_end = bl[i].e;

                    res++;

                }

            }

            start = true;

        }

        return res;

    }

};

//[[2,5],[1,8],[3,10],[4,6],[7,9]]

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。