算法题(day29)- 加油站 & 分发糖果 & 柠檬水找零

134. 加油站 - 力扣(LeetCode)

class Solution(object):
    def canCompleteCircuit(self, gas, cost):
        """
        :type gas: List[int]
        :type cost: List[int]
        :rtype: int
        """
        curSum = 0;
        minSum = float('inf')
        for i in range(len(gas)) :
            rest = gas[i] - cost[i]
            curSum += rest;
            if curSum < minSum :
                minSum = curSum
        if curSum < 0 :
            return -1
        if minSum >= 0:
            return 0
        
        for i in range(len(gas) - 1, -1, -1):
            rest = gas[i] - cost[i]
            minSum += rest
            if minSum >= 0 :
                return i
        return -1        

135. 分发糖果 - 力扣(LeetCode)

先从前先后遍历,按ratings大小比较 + 1;再从后向前遍历,需要一个取最大。

class Solution(object):
    def candy(self, ratings):
        n = len(ratings)
        candy = [1]*n
        for i in range(1, n):
            if ratings[i] > ratings[i - 1]:
                candy[i] = candy[i - 1] + 1
        for i in range(n - 2, -1, -1):
            if ratings[i] > ratings[i + 1]:
                candy[i] = max(candy[i], candy[i + 1] + 1)
        return sum(candy)

860. 柠檬水找零 - 力扣(LeetCode)

这里用三个整形变量存储就行了,用字典是为了练习一下

class Solution(object):
    def lemonadeChange(self, bills):
        n = len(bills)
        _dict = Counter()
        for i in range(n):
            if bills[i] == 5:
                _dict["five"] += 1
            if bills[i] == 10:
                _dict["ten"] += 1
                _dict["five"] -= 1
                if _dict["five"] < 0:
                    return False
            if bills[i] == 20 :
                _dict["two"] += 1
                if _dict['ten'] > 0 :
                    _dict['ten'] -= 1
                    _dict['five'] -= 1
                else :
                    _dict['five'] -= 3
                if _dict['ten'] < 0 or _dict['five'] < 0:
                    return False
        return True

406. 根据身高重建队列 - 力扣(LeetCode)

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

        for p in people :
            que.insert(p[1], p)

        return que

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值