Advertisement
jinhuang1102

134. Gas Station

Jan 15th, 2019
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.26 KB | None | 0 0
  1. """我们首先要知道能走完整个环的前提是gas的总量要大于cost的总量,这样才会有起点的存在。假设开始设置起点start = 0, 并从这里出发,如果当前的gas值大于cost值,就可以继续前进,此时到下一个站点,剩余的gas加上当前的gas再减去cost,看是否大于0,若大于0,则继续前进。当到达某一站点时,若这个值小于0了,则说明从起点到这个点中间的任何一个点都不能作为起点,则把起点设为下一个点,继续遍历。当遍历完整个环时,当前保存的起点即为所求。代码如下:"""
  2. class Solution:
  3.     def canCompleteCircuit(self, gas, cost):
  4.         """
  5.        :type gas: List[int]
  6.        :type cost: List[int]
  7.        :rtype: int
  8.        """
  9.         gasTotal = sum(gas)
  10.         costTotal = sum(cost)
  11.        
  12.         if costTotal > gasTotal:
  13.             return -1
  14.         else:
  15.             total = 0
  16.             _sum = 0
  17.             start = 0
  18.             for i in range(0, len(gas)):
  19.                 total += gas[i] - cost[i]
  20.                 _sum += gas[i] - cost[i]
  21.                 if _sum < 0:
  22.                     start = i + 1
  23.                     _sum = 0
  24.                
  25.             return -1 if total < 0 else start
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement