标题: | Gas Station |
通过率: | 25.7% |
难度: | 中等 |
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.
本题看半天不明白什么意思,网上有一大堆的解法各种动态规划什么的。我感觉都不靠谱,下面我们分析:
先分析暴力破解,就是从每一个点出发计算一次,看看最后是否成立。那么时间复杂度是O(n^2)
其实一遍就能知道,
如从一个点p出发到k时油量小于0,下一次试探肯定是从k开始,
若从k开始刚好可以到数组的最后,那么不用不去测试从数组最后返回前面,
因为若能循环一次那么gas-cost总和一定大于0.所以只用确定有一个点出发可以走到最后,然后看total是否大于0,
具体看代码:
1 class Solution: 2 # @param gas, a list of integers 3 # @param cost, a list of integers 4 # @return an integer 5 def canCompleteCircuit(self, gas, cost): 6 if len(gas)==0 or len(cost)==0 or len(gas)!=len(cost):return -1 7 start,total,sum=0,0,0 8 for i in range(len(gas)): 9 total+=(gas[i]-cost[i]) 10 if sum<0: 11 sum=gas[i]-cost[i] 12 start=i 13 else :sum+=(gas[i]-cost[i]) 14 if total<0:return -1 15 else: return start