Problem 134. Gas Station

Problem:

There are N gas stations along a circular route, where the amount of gas at station i 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, otherwise return -1.

Note:

The solution is guaranteed to be unique.


Solution:

class Solution:
    def canCompleteCircuit(self, gas, cost):
        """
        :type gas: List[int]
        :type cost: List[int]
        :rtype: int
        """
        no_stations = len(gas)
        gas_left = sum(gas)- sum(cost)   # 如果gas总数大于cost,则一定有解
        if gas_left >= 0: # there is a solution
        	start = 0
        	gas_hold = 0
        	while start < no_stations:
        		for route in range(no_stations):
        			gas_hold = gas_hold + gas[(start+route)%no_stations]
        			gas_cost = cost[(start+route)%no_stations]
        			gas_hold = gas_hold - gas_cost
        			if gas_hold < 0:
        				gas_hold = 0
        				start = start + route
        				break
        			
        		if route == no_stations-1 and gas_hold >= 0:
        			return start
        		start = start + 1
        return -1

第一次采用笨拙的全部遍历方法,超时。

该算法注意两个地方:

1. 如果从A不能到达B,则中间的任意一个点均不能到达B。(B为从A出发不能到达的第一个点),所以在搜索A-B不成功,下一次迭代搜索起点可以直接设置为B点。

2.总gas小于总cost时无解。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值