【leetcode 452. 用最少数量的箭引爆气球】贪心策略,局部区间最优解法

链接地址:【leetcode 452. 用最少数量的箭引爆气球】贪心策略,局部区间最优解法

贪心策略:局部区间最优解法,排序后,一次循环遍历
1,按每个气球尾部从大到小排序,给大气球覆盖小气球的可能,确定局部区间右边界递减
2,记录边界值,不断缩小边界
3,当边界值大于下一个气球的尾部坐标,箭+1,重置区间
4,最后的区间,由count = 1;//只要有气球,至少一根箭,记录!

在这里插入图片描述

代码:

class Solution {
public:
    int findMinArrowShots(vector<vector<int>>& points) {
        if(points.empty())
        {
            return 0;
        }
        //按每个气球尾部排序,从大到小
        sort(points.begin(), points.end(), [](vector<int>& prev, vector<int>& next) {
        return prev[1] > next[1];
        });
        int count = 1;              //只要有气球,至少一根箭
        int n = points.size();
        int head = points[0][0];    //左边界
        int tail = points[0][1];    //右边界
        for (int i = 1; i < n; i++)
        {
            //如果左边界大于下一个气球的右值,箭+1,重置区间
            if(head > points[i][1] )
            {
                count++;
                head =0;
                tail = 0;
            }
           if(points[i][0] >= head)
                head = points[i][0];
            if(points[i][1] <= tail)
                tail = points[i][1];
                
        }
        return count;
    }
};

   

如有不足之处,还望指正 [1]


  1. 如果对您有帮助可以点赞、收藏、关注,将会是我最大的动力 ↩︎

posted @ 2021-05-18 09:07  CoutCodes  阅读(54)  评论(0编辑  收藏  举报