134. &55 Gas Station

2018-03-10  本文已影响0人  Jonddy
题目要求:

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.

解题思路:
start, current_sum, total_sum = 0, 0, 0
        for i in range(len(gas)):
            diff = gas[i] - cost[i]
            current_sum += diff
            total_sum += diff
            if current_sum < 0:
                start = i + 1          #放在这个位置很巧妙简直无敌了,这也算贪心吧,如果current_sum < 0 ,从前开始就不行了。
                current_sum = 0

        if total_sum >= 0:
            return start


        return -1

if __name__ == "__main__":
    print(Solution().canCompleteCircuit([1, 2, 3], [3, 2, 1]))
    print(Solution().canCompleteCircuit([1, 2, 3], [2, 2, 2]))
    print(Solution().canCompleteCircuit([1, 2, 3], [1, 2, 3]))
    print(Solution().canCompleteCircuit([1, 2, 3], [1, 2, 4]))


上一篇 下一篇

猜你喜欢

热点阅读