代码随想录训练营第三十四天|860.柠檬水找零406.根据身高重建队列
860.柠檬水找零
局部最优:遇到账单20,优先消耗美元10,完成本次找零。全局最优:完成全部账单的找零。
class Solution {
public:
bool lemonadeChange(vector<int>& bills) {
int five = 0;
int ten = 0;
for(int bill:bills){
if(bill==5){
five++;
}
if(bill==10){
if(five>0){
ten++;
five--;
}
else
return false;
}
if(bill==20){
if(ten>0&&five>0){
ten--;
five--;
}
else if(ten==0&&five>=3){
five--;
five--;
five--;
}
else
return false;
}
}
return true;
}
};
406.根据身高重建队列
局部最优:前面人的身高与本人的身高进行比较,要求与本人第二属性相对应
全局最优:全面身高与属性相应
(遇到两个维度权衡的时候,一定要先确定一个维度,再确定另一个维度)
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) {
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;
}
};