[LeetCode]题解(python):134-Gas Station

题目来源:

  https://leetcode.com/problems/gas-station/


题意分析:

  在一个圈子路线里面有N个汽油站,i站的汽油有gas[i]汽油。现在有一辆无限容量的车,它从i站开到(i+1)需要耗费cost[i]汽油。如果这辆车可以走完这个圈,那么返回这个车的起点,否者返回-1.


题目思路:

  不难发现,如果gas的总和大于或等于cost的总和,必然存在一种路线使得走完整个圈子。那么只要找到一个起点i,从这个起点出发的所有gas的和总比cost的和大就可以了。


代码(python):

class Solution(object):
    def canCompleteCircuit(self, gas, cost):
        """
        :type gas: List[int]
        :type cost: List[int]
        :rtype: int
        """
        begin,subsum,sum,i = 0,0,0,0
        while i < len(gas):
            sum += gas[i] - cost[i]
            subsum += gas[i] - cost[i]
            if subsum < 0:
                subsum,begin = 0,i + 1
            i += 1
        if sum < 0:
            return -1
        else:
            return begin
View Code
原文地址:https://www.cnblogs.com/chruny/p/5354983.html