算法D34 | 贪心算法4 | 860.柠檬水找零 406.根据身高重建队列 452. 用最少数量的箭引爆气球

860.柠檬水找零 

本题看上好像挺难,其实挺简单的,大家先尝试自己做一做。代码随想录

分5/10/20讨论找零方案即可。

Python:

class Solution:
    def lemonadeChange(self, bills: List[int]) -> bool:
        ch5 = 0
        ch10 = 0
        for b in bills:
            if b == 20:
                ch5 -= 1
                if ch10 >=1:
                    ch10 -= 1
                else:
                    ch5 -= 2
            elif b == 10:
                ch5 -= 1
                ch10 += 1
            elif b == 5:
                ch5 += 1
            if ch5<0 or ch10<0:
                return False
        return True

C++:

class Solution {
public:
    bool lemonadeChange(vector& bills) {
        int ch5 = 0;
        int ch10 = 0;
        for (int b: bills) {
            if (b==20) {
                if (ch10>=1) {
                    ch10--;
                    ch5--;
                } else {
                    ch5 -= 3;
                }
            } else if (b==10) {
                ch5--;
                ch10++;
            } else { //b==5
                ch5++;
            }
            if (ch5<0 || ch10<0) return false;
        }
        return true;
    }
};

406.根据身高重建队列 

本题有点难度,和分发糖果类似,不要两头兼顾,处理好一边再处理另一边。代码随想录

关于vector原理讲解:代码随想录

难点在于读懂题目,读懂题目的关键在于递推写清楚case;根据题目直接写出来就是了。

Python:

class Solution:
    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
        people.sort(key=lambda x: (-x[0], x[1]))
        que = []
        for p in people:
            que.insert(p[1], p)
        return que

C++:

class Solution {
static bool cmp(const vector& a, const vector& b) {
    if (a[0]==b[0]) return a[1] < b[1];
    return a[0] > b[0];
}
public:
    vector> reconstructQueue(vector>& people) {
        sort(people.begin(), people.end(), cmp);
        vector> que;
        for (int i=0; i

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

本题是一道 重叠区间的题目,好好做一做,因为明天三道题目,都是 重叠区间。 

https://programmercarl.com/0452.%E7%94%A8%E6%9C%80%E5%B0%91%E6%95%B0%E9%87%8F%E7%9A%84%E7%AE%AD%E5%BC%95%E7%88%86%E6%B0%94%E7%90%83.html

Python:

class Solution:
    def findMinArrowShots(self, points: List[List[int]]) -> int:
        points.sort(key=lambda x: x[0])
        result = 1
        for i in range(1, len(points)):
            if points[i][0] > points[i-1][1]:
                result += 1
            else:
                points[i][1] = min(points[i-1][1], points[i][1])
        return result

C++:

class Solution {
static bool cmp(const vector& a, const vector& b) {
    return a[0] < b[0];
}
public:
    int findMinArrowShots(vector>& points) {
        sort(points.begin(), points.end(), cmp);
        int result=1;
        for (int i=1; i points[i-1][1]) {
                result++;
            } else {
                points[i][1] = min(points[i][1], points[i-1][1]);
            }
        }
        return result;
    }
};

你可能感兴趣的:(算法训练营,算法,数据结构,c++,python,贪心算法)