代码随想录算法训练营第二十九天|LeetCode 134 加油站,LeetCode 135 分发糖果,LeetCode 860 柠檬水找零,LeetCode 406 根据身高重建队列

1.LeetCode 134 加油站

题目链接:134. 加油站

class Solution:
    def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
        curSum = 0
        totalSum = 0
        start = 0

        for i in range(len(gas)):
            curSum += gas[i] - cost[i]
            totalSum += gas[i] - cost[i]

            if curSum < 0:
                start = i + 1
                curSum = 0
        
        if totalSum < 0:
            return -1
        else:
            return start

第一题结束

2.LeetCode 135 分发糖果

题目链接:135. 分发糖果

class Solution:
    def candy(self, ratings: List[int]) -> int:
        candies = [1] * len(ratings)

        for i in range(1, len(ratings)):
            if ratings[i] - ratings[i - 1] > 0:
                candies[i] = candies[i - 1] + 1
        
        for i in range(len(ratings) - 2, -1, -1):
            if ratings[i] - ratings[i + 1] > 0:
                candies[i] = max(candies[i + 1] + 1, candies[i])
        
        return sum(candies)

3.LeetCode 860 柠檬水找零

题目链接:860. 柠檬水找零

class Solution:
    def lemonadeChange(self, bills: List[int]) -> bool:
        five = 0
        ten = 0
        twenty = 0

        for i in bills:
            if i == 5:
                five += 1
            
            if i == 10:
                ten += 1
                five -= 1
                if five < 0:
                    return False
            
            if i == 20:
                twenty += 1
                if ten > 0 and five > 0:
                    ten -= 1
                    five -= 1
                else:
                    if five >= 3:
                        five -= 3
                    else:
                        return False
        
        if ten >= 0 and five >= 0:
            return True
        else:
            return False

第三题结束

4.LeetCode 406 根据身高重建队列

题目链接:406. 根据身高重建队列

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

        for i in people:
            que.insert(i[-1], i)
        
        return que

第四题结束

今天用时1.5h,有点简单了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值