860. 柠檬水找零
模拟找零钱的过程。
class Solution {
public:bool lemonadeChange(vector<int>& bills) {int _5yuan = 0;int _10yuan = 0;int _20yuan = 0;for (int i = 0; i<bills.size(); i++) {if (bills[i] == 5) {_5yuan += 1;}else if (bills[i] == 10) {_10yuan += 1;if (_5yuan >= 1) {_5yuan -= 1;}else {return false;}}else if (bills[i] == 20) {_20yuan += 1;if (_10yuan>=1&&_5yuan>=1) {_10yuan -= 1;_5yuan -= 1;}else if (_5yuan >= 3) {_5yuan -= 3;}else {return false;}}}return true;}
};
406. 根据身高重建队列
先根据身高从高到低排序,如果身高相同角标2数字大的排在后面。然后新建一个结果vector,按照每个位置前面有多少个数排在多少位置。
class Solution {
public:
// 按照身高降序排序,如果身高相同就按照人数升序排序static bool cmp(vector<int> a, 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) {// 存结果的容器vector<vector<int>> queue;// 按照自定义的cmp函数进行大小比较sort(people.begin(), people.end(), cmp);for (int i = 0; i<people.size(); i++) {int position = people[i][1];queue.insert(queue.begin()+position, people[i]);}return queue;}
};
452. 用最少数量的箭引爆气球
只要有气球就至少一支箭,因此结果初始化为零。按照左边界的大小升序排序,如果左边界大于右边界,结果加一;否则处理重叠的情况,将当前段的右边界更新为重叠所有段的右边界的最小值。
class Solution {
public:
// 先按照起始位置排序static bool cmp(vector<int> a, vector<int> b) {return a[0] < b[0];}int findMinArrowShots(vector<vector<int>>& points) {if (points.size() == 0) return 0;sort(points.begin(), points.end(), cmp);// 有零用例的情况已经排除,接下来至少需要用一支箭int res = 1;for (int i = 1; i<points.size(); i++) {// 左边界大于上一个右边界,肯定要加一次射箭if (points[i][0] > points[i-1][1])res++;// 否则重叠,更新右边界为重叠部分较短的右边界else {points[i][1] = min(points[i][1], points[i-1][1]);}}return res;}
};