代码改变世界

LeetCode 134. Gas Station 20170706

2017-07-06 10:40  方小呆dai  阅读(187)  评论(0编辑  收藏  举报

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.

题目大意:在一个环路上有N个加油站。给定两个数组:每个加油站有的油和到下一个加油站需要的油。问从哪个起点开始出发能够走完一圈。

解题思路:本题思路是比较清晰的,从第一个加油站开始遍历每一个加油站,用start保存起点的下标,如果到了某个加油站加的油不够消耗的油用,说明符合条件的起点不可能存在于start和该加油站之间。则新起点设为下一个加油站。原本只想用一个gassum来保存剩下多少油,但是由于不够油的时候该gassum需要清零,则清零后就无法正确判断从新的加油站作为起点的话是否够油开完一圈,结果出错了。因此还需要再增加一个gassum2来保存全程的加油与耗油的差。gassum1则在不够消耗的时候清零重新计算。

class Solution(object):
  def canCompleteCircuit(self, gas, cost):
    """
    :type gas: List[int]
    :type cost: List[int]
    :rtype: int
    """
    start = 0
    gassum1 = 0
    gassum2 = 0
    i = 0
    while i < len(gas):
      gassum2 = gassum2 + gas[i] - cost[i]
      gassum1 = gassum1 + gas[i] - cost[i]
      if gassum1 < 0:
        start = i + 1
        gassum1 = 0
      i += 1
    if gassum2 < 0:
      return -1
    else:
      return start