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

91 阅读2分钟

860. 柠檬水找零

代码随想录文章讲解

贪心

Let's try to simulate giving change to each customer buying lemonade. Initially, we start with no five dollar bills, and no ten dollar bills.

  • If a customer brings a $5 bill, then we take it.

  • If a customer brings a $10 bill, we must return a five dollar bill. If we don't have a five dollar bill, the answer is False, since we can't make correct change.

  • If a customer brings a $20 bill, we must return $15.

    • If we have a $10 and a $5, then we always prefer giving change in that, because it is strictly worse for making change than three $5 bills.
    • Otherwise, if we have three $5 bills, then we'll give that.
    • Otherwise, we won't be able to give $15 in change, and the answer is False.
class Solution:
    def lemonadeChange(self, bills: List[int]) -> bool:
        five, ten = 0, 0
        
        for bill in bills:
            if bill == 5:
                five += 1
            
            if bill == 10:
                if five >= 1:
                    five -= 1
                    ten += 1
                else:
                    return False
            
            if bill == 20:
                if ten >= 1 and five >= 1:
                    ten -= 1
                    five -= 1
                elif five >= 3:
                    five -= 3
                else:
                    return False
        
        return True

406. 根据身高重建队列

代码随想录文章讲解

贪心

  • 本题有两个维度,h和k,看到这种题目一定要想如何确定一个维度,然后在按照另一个维度重新排列。如果两个维度一起考虑一定会顾此失彼

  • 按照身高h来排序呢,身高一定是从大到小排(身高相同的话则k小的站前面),让高个子在前面。

    此时我们可以确定一个维度了,就是身高,前面的节点一定都比本节点高! 那么只需要按照k为下标重新插入队列就可以了。

  • 局部最优:优先按身高高的people的k来插入。插入操作过后的people满足队列属性

  • 全局最优:最后都做完插入操作,整个队列满足题目队列属性

class Solution:
    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
        # 先按照h维度的身高顺序从高到低排序。确定第一个维度
        # lambda返回的是一个元组:当-x[0](维度h)相同时,再根据x[1](维度k)从小到大排序
        people.sort(key=lambda x: (-x[0], x[1]))
        res = []
        for p in people:
            index = p[1]
            res.insert(index, p)
        return res

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

代码随想录文章讲解

贪心

  • 局部最优:当气球出现重叠,一起射,所用弓箭最少。全局最优:把所有气球射爆所用弓箭最少。
  • 为了让气球尽可能的重叠,需要对数组进行排序
# Time complexity: O(NlogN)
# Space complexity: O(N) for sorting
class Solution:
    def findMinArrowShots(self, points: List[List[int]]) -> int:
        if len(points) == 0: 
            return 0
        points.sort(key=lambda x: x[0])
        # points 不为空至少需要一支箭
        res = 1
        
        for i in range(1, len(points)):
            # 气球i和气球i-1不挨着,注意这里不是>=
            if points[i][0] > points[i-1][1]:
                res += 1
            else:
                # 更新重叠气球最小右边界
                points[i][1] = min(points[i][1], points[i-1][1])
        
        return res