代码随想录|贪心III

发布时间 2023-06-23 01:31:47作者: 跪求个offer
860.柠檬水找零 

406.根据身高重建队列 

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

 


 

 

860.柠檬水找零

class Solution:
    def lemonadeChange(self, bills: List[int]) -> bool:
        n1 = 0 #number of 5
        n2 = 0 #number of 10
        for i in bills:
            if i == 5:
                n1 += 1
            elif i == 10:
                if n1 == 0:
                    return False
                n1 -= 1
                n2 += 1
            else:
                if n2 > 0 and n1 > 0:
                    n2 -= 1
                    n1 -= 1
                else:
                    if n1 >= 3:
                        n1 -= 3
                    else:
                        return False
        return True
            

406.根据身高重建队列

遇到两个维度权衡的时候,一定要先确定一个维度,再确定另一个维度。

如果两个维度一起考虑一定会顾此失彼

考虑到以高度为衡量标准,所以我们先将高度从大到小排序

后面按照所需要的前面有多少个比他大或者等于的要求插入排序

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

 


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

遇到范围的问题,一定要思考会不会缩小范围

使用min来解决

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