代码随想录day29 贪心03

134. 加油站

cpp 复制代码
class Solution {
public:
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
        int cursum = 0;
        int totalsum = 0;
        int start = 0;
        for (int i = 0; i < gas.size(); i++) {
            cursum += gas[i] - cost[i];
            totalsum += gas[i] - cost[i];
            if (cursum < 0) {
                start = i + 1;
                cursum = 0;
            }
        }
        if (totalsum < 0)
            return -1;
        return start;
    }
};

135. 分发糖果

cpp 复制代码
class Solution {
public:
    int candy(vector<int>& ratings) {
        vector<int> candys(ratings.size(), 1);
        for (int i = 1; i < ratings.size(); i++) {
            if (ratings[i - 1] < ratings[i]) {
                candys[i] = candys[i - 1] + 1;
            }
        }
        for (int i = ratings.size() - 1; i > 0; i--) {
            if (ratings[i] < ratings[i - 1]) {
                candys[i - 1] = max(candys[i] + 1, candys[i - 1]);
            }
        }
        int sum = 0;
        for (auto a : candys) {
            sum += a;
        }
        return sum;
    }
};

860. 柠檬水找零

cpp 复制代码
class Solution {
public:
    bool lemonadeChange(vector<int>& bills) {
        int bill5 = 0;
        int bill10 = 0;
        for (auto a : bills) {
            if (a == 5) {
                bill5++;
            } else if (a == 10) {
                if (bill5 <= 0)
                    return false;
                bill10++;
                bill5--;
            } else {
                if (bill10 > 0 && bill5 > 0) {
                    bill10--;
                    bill5--;
                } else if (bill5 >= 3) {
                    bill5 -= 3;
                } else {
                    return false;
                }
            }
        }
        return true;
    }
};

406. 根据身高重建队列

cpp 复制代码
class Solution {
public:
    static bool cmp(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) {
        sort(people.begin(), people.end(), cmp);
        vector<vector<int>> que;
        for (int i = 0; i < people.size(); i++) {
            int position = people[i][1];
            que.insert(que.begin() + position, people[i]);
        }
        return que;
    }
};

其实这道题主要是思路,大部分人无法想到按身高降序排序后,第二个参数便是在当前队列里要插入的位置。

相关推荐
Wei&Yan28 分钟前
数据结构——顺序表(静/动态代码实现)
数据结构·c++·算法·visual studio code
团子的二进制世界1 小时前
G1垃圾收集器是如何工作的?
java·jvm·算法
吃杠碰小鸡1 小时前
高中数学-数列-导数证明
前端·数学·算法
故事不长丨1 小时前
C#线程同步:lock、Monitor、Mutex原理+用法+实战全解析
开发语言·算法·c#
long3161 小时前
Aho-Corasick 模式搜索算法
java·数据结构·spring boot·后端·算法·排序算法
近津薪荼1 小时前
dfs专题4——二叉树的深搜(验证二叉搜索树)
c++·学习·算法·深度优先
熊文豪1 小时前
探索CANN ops-nn:高性能哈希算子技术解读
算法·哈希算法·cann
熊猫_豆豆2 小时前
YOLOP车道检测
人工智能·python·算法
艾莉丝努力练剑2 小时前
【Linux:文件】Ext系列文件系统(初阶)
大数据·linux·运维·服务器·c++·人工智能·算法
偷吃的耗子2 小时前
【CNN算法理解】:CNN平移不变性详解:数学原理与实例
人工智能·算法·cnn