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

发布时间 2023-11-14 13:09:00作者: 忆象峰飞

860.柠檬水找零

class Solution:
    def lemonadeChange(self, bills: List[int]) -> bool:
        five, ten, twenty = 0, 0, 0
        for bill in bills:
            if bill == 5:
                five += 1

            elif bill == 10:
                if five <= 0:
                    return False
                five -= 1
                ten += 1

            elif bill == 20:
                if ten > 0 and five > 0:
                    ten -= 1
                    five -= 1
                    twenty += 1
                elif five >= 3:
                    five -= 3
                    twenty += 1
                else:
                    return False
        return True

406.根据身高重建队列

class Solution:
    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
        # 先按身高降序排,升高相同再按 k 的升序排
        people.sort(key=lambda x:(-x[0], x[1]))

        que = []
        # 再按 k 插入到 people 数组
        for i in people:
            que.insert(i[1], i)

        return que

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

class Solution:
    def findMinArrowShots(self, points: List[List[int]]) -> int:
        points.sort(key=lambda x: (x[0], x[1]))
        count = 1
        for i in range(1, len(points)):
            # 不在区间内或者弓箭位置不在区间内
            if points[i][0] > points[i-1][1]:
                count += 1
            else: 
                # 更新右边界              
                points[i][1] = min(points[i-1][1], points[i][1])
        return count