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;
    }
};
相关推荐
wljy121 小时前
二、静态库的制作和使用
linux·c语言·开发语言·c++
道剑剑非道1 天前
FFmpeg 6.0 实战:用 C++ 封装摄像头采集与 RTSP 推流
开发语言·c++·ffmpeg
灵智实验室1 天前
PX4状态估计技术EKF2详解(二):EKF2 误差状态动力学与协方差传播
算法·无人机·px 4
米粒11 天前
力扣算法刷题 Day 64 Floyd算法 & A* 算法 & 总结篇
算法·leetcode·职场和发展
北顾笙9801 天前
LLM学习-day05
学习
光电笑映1 天前
从环境变量到进程虚拟地址空间——Linux 内存管理的底层脉络
linux·服务器·c++·c
XX風1 天前
OpenGL中Face culling 面剔除的具体实现
算法·图形渲染
IT猿手1 天前
光伏模型参数估计:基于山羊优化算法(GOA )的光伏模型参数辨识问题求解研究,免费提供完整MATLAB代码链接
开发语言·算法·matlab·群智能优化算法·智能优化算法·光伏模型参数估计·光伏模型参数辨识
sparEE1 天前
c++字符串和自定义字面量
开发语言·c++
麻雀飞吧1 天前
期货量化策略讲解:天勤量化下的跨期价差均值回归策略实战
python·算法·均值算法·回归