【leetcode/python/134】Gas Station

题目

https://leetcode.com/problems/gas-station/

题目太长了,还是直接贴链接吧~
题目很长,但是理解起来还是比较容易的:

在一条环形的路上有N个加油站,每个加油站里有gas[i]的汽油,从第i个加油站到第i+1个加油站需要花费cost[i]的汽油。假设汽车的油箱可以装无数的汽油,判断一辆没有油的汽车是否可以从其中的某一个加油站出发并行驶一圈后返回该加油站。如果可以的话,返回起始加油站的下标,否则返回-1。

实现代码

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
        length = len(gas)
        
        startIndex,diff  = 0,0
        for i in range(length):
            if gas[i] + diff < cost[i]:
                startIndex = i + 1
                diff = 0
            else:
                diff += gas[i]- cost[i]
        return startIndex
               
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值