leetcode-134-加油站

题目描述:

 

 方法一:O(n^2) (超时)

class Solution:
    def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
        for i in range(len(gas)): 
            if gas[i]-cost[i] < 0: 
                pass 
            else: 
                Flag = True 
                store = gas[i]-cost[i] 
                for step in range(1, len(gas)+1): 
                    move = (i+step)%len(gas) 
                    store += gas[move] -cost[move] 
                    if store < 0: 
                        Flag = False 
                        break 
                if Flag: 
                    return i 
        return -1

方法二:官方解法 O(n) O(1)

class Solution:
    def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
        n = len(gas) 
        total_tank, curr_tank = 0, 0 
        starting_station = 0 
        for i in range(n): 
            total_tank += gas[i] - cost[i] 
            curr_tank += gas[i] - cost[i] 
            # If one couldn't get here, 
            if curr_tank < 0: 
                # Pick up the next station as the starting one. 
                starting_station = i + 1
                # Start with an empty tank.
                curr_tank = 0 
        return starting_station if total_tank >= 0 else -1

 

posted @ 2019-07-16 16:18  oldby  阅读(292)  评论(0编辑  收藏  举报