Day35 贪心算法 part04 860. 柠檬水找零 406. 根据身高重建队列 452. 用最少数量的箭引爆气球

贪心算法 part04 860. 柠檬水找零 406. 根据身高重建队列 452. 用最少数量的箭引爆气球

860. 柠檬水找零

c 复制代码
class Solution {
public:
    bool lemonadeChange(vector<int>& bills) {
        vector<int> count(2,0); //count[0]记录5美元,count[1]记录10美元
        for(int i = 0; i<bills.size();i++){
            if(bills[i]==5) count[0]++;
            else if(bills[i]==10){
                if(count[0]<=0) return false;
                else{
                    count[0]--;
                    count[1]++;
                }
            }
            else if(bills[i]==20){ 
                if(count[1]<=0){ //如果10美元没有,我们尝试找零3个5美元
                    count[0]-=3;
                }else{ //有10美元,找零一个5美元+一个10美元
                    count[0]--;
                    count[1]--;
                }
                if(count[0]<0) return false; //如果5美元用光,没法找零
            }
        }
        return true;
    }
};

406. 根据身高重建队列

尤其注意vector扩容机制对时间的消耗,优先采用list链表存储

c 复制代码
class Solution {
public:
    static bool Compare(const vector<int>& a, const vector<int>& b) {
        if (a[0] == b[0]) return a[1] < b[1];
        return a[0] > b[0];
    }
    vector<vector<int>> reconstructQueue(vector<vector<int>>& people) {
        list<vector<int>> que; //记录结果
        sort (people.begin(), people.end(), Compare); //排序操作,身高从高到低
        for(int i = 0; i< people.size();i++){
            int pos = people[i][1];
            list<vector<int>>::iterator it = que.begin();
            while(pos--){ //it只会遍历到que.end()位置
                it++;
            }
            que.insert(it,people[i]);
        }
        return vector<vector<int>>(que.begin(),que.end());
    }
};

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

c 复制代码
class Solution {
private:
static bool Compare(const vector<int>& a, const vector<int>& b) {
    return a[0] < b[0];
}
public:
    int findMinArrowShots(vector<vector<int>>& points) {
        if (points.size() == 0) return 0;
        sort(points.begin(), points.end(), Compare);

        int result =1; //记录结果
        for(int i = 0; i<points.size()-1;i++){
            if(points[i][1] <points[i+1][0]) result++;  //上个气球右边界小于下个气球左边界,二者无重叠区间
            else{
                points[i+1][1] = points[i+1][1] < points[i][1] ?  points[i+1][1] : points[i][1];
            }
        }
        return result;
    }
};
相关推荐
Navigator_Z4 小时前
LeetCode //C - 1332. Remove Palindromic Subsequences
c语言·算法·leetcode
Code_Solitude4 小时前
c语言:期末复习(7)
c语言·开发语言·算法
潇湘散客4 小时前
PlantAis插件更新:RVM负实体开关;VUE文件读取与导出等
c++·qt·opengl
DKPT4 小时前
AI编程助手新利器skills火爆登场
人工智能·笔记·学习·开源·ai编程
往谏不追4 小时前
零基础掌握Prompt Engineering工程
学习·prompt
金榜题名萱4 小时前
蓝桥杯 - 旗帜
c语言·数据结构·c++·算法·蓝桥杯
俊俊几年的5 小时前
RK3588 硬件架构详解:CPU、GPU、NPU 与 RKNN 软件栈
linux·c++·python·yolo·numpy·rockchip
yiangL_5 小时前
自主学习:Python 嵌套循环实验|双层循环与图形打印实践
开发语言·python·学习
艾利克斯冰5 小时前
开发学习资源合集|电子书 + 多平台工具包,一站式整理
学习
Rain的Java大神之路5 小时前
LeetCode 46 全排列:从「及格答案」到让面试官眼前一亮的三种写法
后端·leetcode·面试