首页 > 代码库 > Leetcode 134 Gas Station
Leetcode 134 Gas Station
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.
这道题最容易想到的方法就是从一个点出发,看看能不能走回到起点,如果可以返回起点的index, 不行的话再试下一个点。但是超时。
这个超时算法中有两点值得注意。
a) L13. 对于 int a 怎么计算 a 在 循环群[0,1,2,n-1]上的index?
b) L21-L22,可以使用一个变量记录是哪一步跳出的。然后判断是不是最后一步跳出的。
1 class Solution(object): 2 def canCompleteCircuit(self, gas, cost): 3 """ 4 :type gas: List[int] 5 :type cost: List[int] 6 :rtype: int 7 """ 8 n = len(gas) 9 for i in range(n): 10 fule = 0 11 step = 0 12 for j in range(n): 13 index = (i+j +1)%n -1 14 fule += gas[index] 15 step = j 16 if fule < cost[index]: 17 break 18 else: 19 fule -= cost[index] 20 21 if step == n-1: 22 return i 23 return -1
一下三条原则摘自: http://bangbingsyb.blogspot.com/2014/11/leetcode-gas-station.html
性质1. 对于任意一个加油站i,假如从i出发可以环绕一圈,则i一定可以到达任何一个加油站。显而易见。
1 class Solution(object): 2 def canCompleteCircuit(self, gas, cost): 3 """ 4 :type gas: List[int] 5 :type cost: List[int] 6 :rtype: int 7 """ 8 n = len(gas) 9 start = 0 10 netGasSum = 0 11 curGasSum = 0 12 13 for i in range(n): 14 netGasSum += gas[i] - cost[i] 15 curGasSum += gas[i] - cost[i] 16 if curGasSum < 0: 17 start = i+1 18 curGasSum = 0; 19 20 if netGasSum < 0: 21 return -1 22 return start
Leetcode 134 Gas Station