Leetcode刷题记录——134. 加油站

在这里插入图片描述
官方解法:
遍历一次
每一次都维护三个值

一个是从0出发 到现在 油箱里汽油的数量(就算中间是负数 中断也没关系)

第二个是到目前为止 没有中断的情况下 油箱里汽油的数量(如果中间中断了 记作0 )

第三个 是 起始站的序号 如果中间中断了 从下一个开始(如果当前维护的第二个量<0 则这个量+=1)

从头遍历到尾
如果最后第一个变量 大于等于0
返回第三个量 否则-1

class Solution:
    def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
        suma = 0
        cura = 0
        start = 0
        for i in range(len(gas)):
            suma += gas[i] - cost[i]
            cura += gas[i] - cost[i]
            if cura < 0:
                cura = 0
                start = i + 1
        return start if suma >= 0  else -1 

我自己的方法:

class Solution:
    def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
        newlist = []
        for i in range(len(gas)):
            newlist.append(gas[i]-cost[i])
        if sum(newlist) < 0:
            return -1
        if len(newlist)<=1:
            return 0
        else:
            index_list=[]
            for i in range(len(newlist)):
                if i == 0:
                    if newlist[-1] < 0 and newlist [0] >= 0:
                        index_list.append(0)
                elif i > 0:
                    if newlist[i-1] < 0 and newlist[i] >= 0:
                        index_list.append(i)
            for i,each_start in enumerate(newlist):
                templist = newlist[i:] + newlist[:i]
                base = 0
                for j in templist:
                    base += j
                    if base < 0:
                        break
                else:
                    return i
            return -1 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值