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

题目链接:134. 加油站 - 力扣(LeetCode)

思路:首先如果gas的总和小于cost的总和,那么无论如何都跑不到一圈。接下来就算每天的rest[i] = gas[i] - cost[i]。如果当天的rest累加为负值时,那么就不可能从当前位置出发跑一圈。也就是要从下一个七点开始重新累计。

class Solution(object):
    def canCompleteCircuit(self, gas, cost):
        """
        :type gas: List[int]
        :type cost: List[int]
        :rtype: int
        """
        if sum(gas) < sum(cost):
            return -1

        rest = [gas[i] - cost[i] for i in range(len(gas))]
        curSum = 0
        totalSum = 0
        startIndex = 0
        for i in range(len(rest)):
            curSum += rest[i]
            if curSum < 0:
                startIndex = i + 1
                curSum = 0

        return startIndex
        

题目链接:135. 分发糖果 - 力扣(LeetCode)

思路:想到了两次贪心的思路,但是从后向前的result[i]的设置没有考虑周全,因为有两种选择。一:如果本身result[i-1] 的值就比result[i]大的话就选result[i-1],如果两个相等就选result[i]+1

class Solution(object):
    def candy(self, ratings):
        """
        :type ratings: List[int]
        :rtype: int
        """

        result = [1] * len(ratings)

        for i in range(len(result) - 1):
            if ratings[i+1] > ratings[i]:
                result[i+1] = result[i] + 1


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

        return sum(result)

题目链接:860. 柠檬水找零 - 力扣(LeetCode)

思路:模拟题

class Solution(object):
    def lemonadeChange(self, bills):
        """
        :type bills: List[int]
        :rtype: bool
        """

        five = 0
        ten = 0
        twenty = 0

        for x in bills:
            if x == 5:
                five += 1
            
            elif x == 10:
                if five <= 0:
                    return False
                else:
                    ten += 1
                    five -= 1

            elif x == 20:
                if ten <= 0:
                    if five < 3:
                        return False
                    else:
                        five -= 3
                else:
                    if five <= 0:
                        return False
                    else:
                        five -= 1
                        ten -= 1

        return True
        

题目链接:406. 根据身高重建队列 - 力扣(LeetCode)

思路:对身高进行排序,然后根据后序的值将元组插入新数组。

class Solution(object):
    def reconstructQueue(self, people):
        """
        :type people: List[List[int]]
        :rtype: List[List[int]]
        """

        people.sort(key = lambda x : (-x[0], x[1]))

        result = []

        for x in people:
            result.insert(x[1], x)

        return result

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值