代码随想录算法训练营第三十五天| 860 柠檬水找零 406 根据身高重建队列 452 用最少数量的箭引爆气球
创始人
2025-06-01 07:16:55

代码随想录算法训练营第三十五天| 860 柠檬水找零 406 根据身高重建队列 452 用最少数量的箭引爆气球

LeetCode 860 柠檬水找零

题目链接: 860.柠檬水找零

思路:

局部最优:遇到账单5,直接收下;遇到账单10,消耗一个5,增加一个10;遇到账单20,优先消耗美元10,完成本次找零。

全局最优:完成全部账单的找零。

class Solution {
public:bool lemonadeChange(vector& bills) {int five = 0, ten = 0, twenty = 0;for (int bill : bills) {// 情况一if (bill == 5) five++;// 情况二if (bill == 10) {if (five <= 0) return false;ten++;five--;}// 情况三if (bill == 20) {// 优先消耗10美元,因为5美元的找零用处更大if (five > 0 && ten > 0) {five--;ten--;twenty++; } else if (five >= 3) {five -= 3;twenty++; // 同理,这行代码也可以删了} else return false;}}return true;}
};

LeetCode 406 根据身高重建队列

题目链接: 406.根据身高重建队列

局部最优:优先按身高高的people的k来插入。插入操作过后的people满足队列属性

全局最优:最后都做完插入操作,整个队列满足题目队列属性

class Solution {
public:static bool cmp(const vector& a, const vector& b) {if (a[0] == b[0]) return a[1] < b[1];return a[0] > b[0];}vector> reconstructQueue(vector>& people) {sort (people.begin(), people.end(), cmp);vector> que;for (int i = 0; i < people.size(); i++) {int position = people[i][1];que.insert(que.begin() + position, people[i]);}return que;}
};

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

题目链接: 452.用最少数量的箭引爆气球

class Solution {
private:static bool cmp(const vector& a, const vector& b) {return a[0] < b[0];}
public:int findMinArrowShots(vector>& points) {if (points.size() == 0) return 0;sort(points.begin(), points.end(), cmp);int result = 1; // points 不为空至少需要一支箭for (int i = 1; i < points.size(); i++) {if (points[i][0] > points[i - 1][1]) {  // 气球i和气球i-1不挨着,注意这里不是>=result++; // 需要一支箭}else {  // 气球i和气球i-1挨着points[i][1] = min(points[i - 1][1], points[i][1]); // 更新重叠气球最小右边界}}return result;}
};

相关内容

热门资讯

今年我省粮食产量达515.56... (来源:辽宁日报)转自:辽宁日报 图为在中储粮(盘锦)储运有限公司,装运粮食的重型卡车排起长队...
国家发展改革委部署促进投资止跌... (来源:辽宁日报)转自:辽宁日报 新华社北京12月13日电 (记者魏玉坤) 记者13日从全国发展和改...
江苏省实施《中华人民共和国森林... (来源:新华日报) 目 录 第一章 总则 第二章 森林、林木和林地权属管理...
姜堰数字化产品讲“活”理论 (来源:新华日报) □ 本报记者 卢佳乐 通讯员 姜宣 “王教授,您约我‘喝茶论道’,...
联合国维和部队在苏丹遇袭 6人... 转自:财联社【联合国维和部队在苏丹遇袭 6人死亡】财联社12月14日电,当地时间13日,苏丹武装部队...