边工作边刷题:70天一遍leetcode: day 11-2

Gas Station

老题,这种circular的题一般都能转化成单向的。比如这题就是用sumDiff来判断是否有解,而start单向递增。

class Solution(object):
    def canCompleteCircuit(self, gas, cost):
        """
        :type gas: List[int]
        :type cost: List[int]
        :rtype: int
        """
        sumGas = 0
        sumDiff = 0
        start = 0
        n = len(gas)
        for i in range(n):
            diff = gas[i]-cost[i]
            sumDiff+=diff
            if sumGas+diff<0:
                start=i+1
            else:
                sumGas+=diff
        
        if sumDiff>=0:
            return start
        else:
            return -1

posted @ 2016-05-12 10:59  absolute100  阅读(111)  评论(0编辑  收藏  举报