思路:
局部最优:遇到账单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;}
};
局部最优:优先按身高高的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;}
};
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;}
};