860.柠檬水找零
https://leetcode.cn/problems/lemonade-change/
class Solution {
public:
bool lemonadeChange(vector<int>& bills) {
int _5 = 0;
int _10 = 0;
for (int i = 0; i < bills.size(); i++) {
if (bills[i] == 5) _5++;
else if (bills[i] == 10) {
if(_5) {
_5--;
_10++;
}
else return false;
}
else if (bills[i] == 20) {
if(_10 && _5) {
_10--;
_5--;
}
else if(_5 >= 3) {
_5 -= 3;
}
else return false;
}
}
return true;
}
};
406.根据身高重建队列
https://leetcode.cn/problems/queue-reconstruction-by-height/
用vector
class Solution {
public:
static bool myCmp(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) {
sort(people.begin(), people.end(), myCmp);
vector<vector<int>> result;
for (int i = 0; i < people.size(); i++) {
int k = people[i][1];
result.insert(result.begin() + k, people[i]);
}
return result;
}
};
用list
class Solution {
public:
static bool myCmp(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) {
sort(people.begin(), people.end(), myCmp);
list<vector<int>> result;
for (int i = 0; i < people.size(); i++) {
int k = people[i][1];
auto iter = result.begin();
while(k--) iter++;
result.insert(iter, people[i]);
}
return vector<vector<int>> (result.begin(), result.end());
}
};
452. 用最少数量的箭引爆气球
https://leetcode.cn/problems/minimum-number-of-arrows-to-burst-balloons/
左对齐:
class Solution {
public:
static bool myCmp(vector<int> &A, vector<int> &B) {
return A[0] < B[0];
}
int findMinArrowShots(vector<vector<int>>& points) {
if (points.empty()) return 0;
sort(points.begin(), points.end(), myCmp);
int result = 1;
for (int i = 1; i < points.size(); i++) {
if(points[i][0] > points[i - 1][1]) {
result++;
}
else {
points[i][1] = min(points[i][1], points[i - 1][1]);
}
}
return result;
}
};
右对齐:
class Solution {
public:
static bool myCmp(vector<int> &a, vector<int> &b) {
return a[1] < b[1];
}
int findMinArrowShots(vector<vector<int>>& points) {
if (points.empty()) return 0;
sort(points.begin(), points.end(), myCmp);
int count = 1;
int end = points[0][1];
for (int i = 0; i < points.size(); i++) {
if (end < points[i][0]) {
count++;
end = points[i][1];
}
}
return count;
}
};