代码随想录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;
    }
};

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

相关推荐
alphaTao5 分钟前
LeetCode 每日一题 2026/3/16-2026/3/22
linux·windows·leetcode
空空潍6 分钟前
LeetCode力扣 hot100一刷完结
算法·leetcode
leaves falling9 分钟前
搜索插入位置(第一个≥target的位置)
算法
lcreek9 分钟前
LeetCode 1162.地图分析
算法·leetcode·bfs
寒月小酒12 分钟前
3.20 OJ
算法
AI科技星15 分钟前
基于空间光速螺旋归一化的动力学方程推导与数值验证
人工智能·线性代数·算法·机器学习·平面
bbbb36519 分钟前
排序算法的演进史:从冒泡到快速再到TimSort的技术7
数据结构·算法·排序算法
不染尘.23 分钟前
排序算法详解1
开发语言·数据结构·c++·算法·排序算法
Tisfy25 分钟前
LeetCode 3567.子矩阵的最小绝对差:暴力模拟
leetcode·矩阵·题解·模拟·暴力