题目
解题方法:模拟+贪心法
该题采用模拟买卖的方法,不必多说。值得一提的是其中运用到了一点贪心的思想,即收到20元时,应优先采取找零10元+5元的策略,而不是找零3个5元,因为5元更加通用,既能找零10元,也能找零20元。
代码实现:
class Solution {
public:
bool lemonadeChange(vector<int>& bills) {
int five, ten, twenty;
five = ten = twenty = 0;
for (int i = 0; i < bills.size(); i++) {
if (bills[i] == 5) {
five++;
continue;
}
if (bills[i] == 10) {
if (five == 0)
return false;
else {
ten++;
five--;
}
}
if (bills[i] == 20) {
// 这里运用了贪心的思想,优先检查能否使用10元+5元来找零
if (ten > 0 && five > 0) {
five--;
ten--;
twenty++;
} else if (five > 2){
five -= 3;
twenty++;
} else {
return false;
}
}
}
return true;
}
};