https://leetcode.com/problems/gas-station/
类比jump game https://leetcode.com/problems/jump-game/
思路1:贪心 O(n)
思路就是贪心。子问题就是判断车在第i个position的时候是否可以到达i+1个position,条件就是当前第i个position所加的油gas[i] + diff(就是到达第i个position时剩下来的油,可以看做前面几站提供的补给) 大于等于cost[i]。
这里首先要判断当sum(gas) < sum(cost)则无解。
res_index 初始化为0
然后从i = 0开始,逐渐递增,直到第i个站不能到达第i+1个站的话,常规思路就是再令res_index ==1,然后继续i = res_index开始递增,。。。直到找到res_index. 这就是常规的O(n^2)思路。但是会TLE.
其实在res_index = 0, 然后遇到第i = k个站不能到达第i+1个站,这个时候其实只需要继续试探 res_index> i就行,因为如果从 0< res_index <i+1 <script type="math/tex" id="MathJax-Element-13"> 0< res_index <i+1 <script type="math/tex" id="MathJax-Element-15">
其实这里res_index从k+1开始试探,数值上也不一定能保证,能车子能从第k站到第k+1站,e.g. 第k站到第k+1站路途遥远,耗油非常大。因为这里题目保证了肯定有解,那么就可以消除这个顾虑了
class Solution(object):
def canCompleteCircuit(self, gas, cost):
"""
:type gas: List[int]
:type cost: List[int]
:rtype: int
"""
if sum(gas) < sum(cost): return -1
n = len(gas)
diff = 0
stationIndex = 0
for i in range(n):
if gas[i]+diff < cost[i]: stationIndex = i+1; diff = 0
else: diff += gas[i]-cost[i]
return stationIndex
思路2:常规遍历 O(n^2)
这里要想到如果把O(n^2)降到O(n)
自己的办法是O(n^2)的,所以TLE了。
class Solution(object):
def canCompleteCircuit(self, gas, cost):
"""
:type gas: List[int]
:type cost: List[int]
:rtype: int
"""
if sum(gas) < sum(cost): return -1
for i in xrange(len(cost)):
balance = gas[i]
j = i + 1
while j < len(cost):
#print (j, balance, cost[j-1])
if balance < cost[j-1]:
break
else:
balance = balance - cost[j - 1] + gas[j]
j += 1
#print 'part1 = %d %d' %(i,j)
if j != len(cost):
continue
j = 0
while j <= i:
if balance < cost[j - 1]:
break
else:
balance = balance - cost[j - 1] + gas[j]
j += 1
#print 'part2 = %d %d' %(i,j)
if j != i + 1:
continue
return i