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.

解题方法

  1. 如果总油量小于消耗量,那么无解,否则必然有一个解

  2. 解法

  3. 遍历各个index, 用total记录到现在积累的油量

  4. 对于i, 如果积累的油量total + 加油站的油量gas[i] < cost[i],说明无法到达下一个stop,那么就将
  5. station设为i+1, 因为i之前的stop都不能当做起点,否则无法达到i+1

Solution

class Solution(object):
    def canCompleteCircuit(self, gas, cost):
        """
        :type gas: List[int]
        :type cost: List[int]
        :rtype: int
        """
        if not gas or not cost:
            return -1

        if sum(gas) < sum(cost):
            return -1

        length = len(gas)
        total = 0
        station = 0

        for i in range(length):
            if total + gas[i] < cost[i]:
                total = 0
                station = i + 1
            else:
                total += gas[i] - cost[i]

        return station

Reference