LeetCode #134 Gas Station

【问题描述】

There are N gas stations along a circular route, where the amount of gas at station is gas[i].

You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.

Return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return -1.

Note:

  • If there exists a solution, it is guaranteed to be unique.
  • Both input arrays are non-empty and have the same length.
  • Each element in the input arrays is a non-negative integer.


【解决思路】

这道题目有两个比较关键的量。

一个是总量total,从站点0一直累计到最后一个站点。

另一个是累积量cumulation,如果累积到某个站点时cumulation<0(油量耗尽),则从下一个站点开始累积(更新累积的起点start)。

如果到最后total>=0(总加油量不小于耗油量),则说明遍历成功,返回累积的起点(start);否则说明遍历失败,返回-1。


【代码实现】

class Solution:
    def canCompleteCircuit(self, gas, cost):
        """
        :type gas: List[int]
        :type cost: List[int]
        :rtype: int
        """
        num = len(gas)
        start = 0
        total = 0   # 总量(0~num)
        cumulation = 0  # 累计量(start~num)
        for i in range(0, num):
            total = total + gas[i] - cost[i]
            cumulation = cumulation + gas[i] - cost[i]
            # 如果邮箱空了,从下一个站点重新开始累积
            if cumulation < 0:
                start = i + 1
                cumulation = 0
        return (start if total >= 0 else -1)

'''
sol = Solution()
gas  = [1,2,3,4,5]
cost = [3,4,5,1,2]
print(sol.canCompleteCircuit(gas, cost))

gas  = [2,3,4]
cost = [3,4,3]
print(sol.canCompleteCircuit(gas, cost))
'''
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值