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

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

相关推荐
byte轻骑兵4 分钟前
【LE Audio】CSIP精讲[5]: 蓝牙协同设备组的安全防护体系与实战规范
算法·安全·音频·le audio·低功耗音频
剑挑星河月6 分钟前
35.搜索插入位置
java·数据结构·算法·leetcode
闪电悠米17 分钟前
力扣hot100-438.找到字符串中所有字母异位词-固定长度滑动窗口详解
linux·服务器·数据结构·算法·leetcode·滑动窗口·力扣hot100
人道领域24 分钟前
【LeetCode刷题日记】51.N皇后
数据结构·算法
芝士爱知识a9 小时前
AI 模拟面试怎么做:智蛙公考智能体多轮对话 + 实时追问的工程实现
面试·职场和发展
古城小栈9 小时前
为啥说:训练用BF16,推理用FP16
人工智能·算法·机器学习
KaMeidebaby9 小时前
卡梅德生物技术快报|蛋白 N 端测序在重组贻贝融合蛋白表征中的应用,解决原核表达序列偏移工艺难题
前端·人工智能·物联网·算法·百度
Turbo正则10 小时前
群论在AI中的应用概述
人工智能·算法·抽象代数
ysa05103010 小时前
【并查集】判环
c++·笔记·算法
Jerry10 小时前
KeetCode 44. 开发商购买土地
算法