[Lintcode]187. Gas Station/[Leetcode]134. Gas Station

187. Gas Station/134. Gas Station

  • 本题难度: Medium
  • Topic: Greedy

Description

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.

Example
Given 4 gas stations with gas[i]=[1,1,3,1], and the cost[i]=[2,2,1,1]. The starting gas station's index is 2.

Challenge
O(n) time and O(1) extra space

Notice
The solution is guaranteed to be unique.

我的代码

class Solution:
    """
    @param gas: An array of integers
    @param cost: An array of integers
    @return: An integer
    """
    def canCompleteCircuit(self, gas, cost):
        # write your code here
        n = len(gas)
        min_one = gas[0] - cost[0]
        pos = 0
        tmp = 0
        for i in range(n):
            tmp += gas[i] - cost[i]
            if tmp < min_one:
                min_one = tmp
                pos = i
        pos = (pos+1)%n
        res = 0
        for j in range(n):
            k = (j + pos) % n
            res += gas[k] - cost[k]
            if res < 0:
                return -1
        return pos

别人的代码

思路

最保险的情况,肯定是把最费油的留在最后面。
假设从第0个加油站开始,油箱在第i+1个位置为第i个位置累积的油量+第i个加油站加油量-从第i个到第i+1消耗的油量。虽然出现了负值,但是可以体现整体的情况。

  • 时间复杂度
    O(log(n))
  • 出错
    一开始只考虑到了第i个加油站加油量-从第i个到第i+1消耗的油量,没考虑到累积情况。
上一篇:安装Ubuntu 20.04 以后


下一篇:android – 如何在zxing中触发批量模式扫描