代码随想录算法训练营第36天 [860.柠檬水找零 406.根据身高重建队列 452. 用最少数量的箭引爆气球 ]

发布于:2024-06-16 ⋅ 阅读:(18) ⋅ 点赞:(0)

代码随想录算法训练营第36天 [860.柠檬水找零 406.根据身高重建队列 452. 用最少数量的箭引爆气球 ]


一、860.柠檬水找零

链接: 代码随想录.
思路:十块只能找五块,二十能找十块五块和三个五块,优先消耗十块
做题状态:看解析后做出来了

class Solution {
public:
    bool lemonadeChange(vector<int>& bills) {
        int five = 0, ten = 0, twenty = 0;
        cout << five << " " << ten << " " << twenty << endl;
        for (int bill : bills) {
            if (bill == 5) {
                five++;
            } else if (bill == 10) {
                if (five == 0) {
                    return false;
                }
                ten++;
                five--;
            } else if (bill == 20) {
                if (ten > 0 && five > 0) {
                    ten--;
                    five--;
                    twenty++;
                } else if (five >= 3) {
                    five -= 3;
                    twenty++;
                } else {
                    return false;
                }
            }
            cout << five << " " << ten << " " << twenty << endl;
        }
        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<vector<int>> reconstructQueue(vector<vector<int>>& people) {
         sort(people.begin(), people.end(), cmp);
         vector<vector<int>> result;
         for (vector<int> pos : people) {
             int position = pos[1];
             result.insert(result.begin() + position, pos);
         }

         return result;
     }
	//用链表,插入的效率更高
    vector<vector<int>> reconstructQueue(vector<vector<int>>& people) {
        sort(people.begin(), people.end(), cmp);
        list<vector<int>> que;
        for (vector<int> pos : people) {
            int position = pos[1];
            auto it = que.begin();
            while(position--){
                it++;
            }
            que.insert(it,pos);
        }

        return vector<vector<int>>(que.begin(),que.end());
    }
};

三、452. 用最少数量的箭引爆气球

链接: 代码随想录.
思路:如果有重合,那就更新下一个点的右边界(当前点右边界和下一个点有边界的最小值)
做题状态:看解析后做出来了

class Solution {
public:
    static bool cmp(vector<int> a, vector<int> b) { return a[0] < b[0]; }

    int findMinArrowShots(vector<vector<int>>& points) {
        sort(points.begin(), points.end(), cmp);
        int result = 1;
        for (int i = 0; i < points.size() - 1; i++) {
            // 当前的右边界小于下一个的左边界,肯定不重合
            cout << points[i][0] <<" " <<points[i][1] <<" ";
            if (points[i][1] < points[i + 1][0]) {
                result++;
            } else {
                // 有重合,合并当前的和下一个的有边界
                points[i + 1][1] = min(points[i][1], points[i + 1][1]);
            }
        }
        return result;
    }
};