[Lintcode]187. Gas Station/[Leetcode]134. Gas Station
Posted siriusli
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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消耗的油量,没考虑到累积情况。
以上是关于[Lintcode]187. Gas Station/[Leetcode]134. Gas Station的主要内容,如果未能解决你的问题,请参考以下文章
1033 To Fill or Not to Fill (25分)