1. 程式人生 > >演算法分析與設計第七週:134. Gas Station

演算法分析與設計第七週:134. Gas Station

題目簡介:
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.

提煉內容:
何為合法出發點:
1、該點p的pCost值小於pGas值
2、該點的後續節點q,若其qCost值大於qGas值,那麼p中汽油剩餘值(remainingGas = pGas - pCost) + qGas >= qCost
3、以此類推

演算法思想:
1、找出所有的非法出發點
2、將非法出發點存入list unablePos
3、不在list中的出發點即為合法出發點
4、若出發點全在list中,則無合法出發點,程式返回-1

程式碼:

class Solution(object):
    def canCompleteCircuit(self, gas, cost)
:
#分別表示剩餘汽油和所需汽油 remainingGas , needGas, i = 0, 0, 0 #用於儲存非法出發點 unablePos = [] size = len(gas) #對每個出發點進行遍歷並判斷其是否合法 while i < size: #遇到非法出發點 if gas[i] < cost[i]: #儲存非法出發點 unablePos.append(i) #若下一個點是合法出發點,則從該出發點反序遍歷
#即遇到了gas: 3 4 5 第三個出發點 # cos: 2 3 6 if gas[(i + 1) % size] >= cost[(i + 1) % size]: #得到該節點需要的汽油量 needGas = cost[i] - gas[i] index = i #反序遍歷直到前面的剩餘汽油量達到需要汽油量值 while remainingGas < needGas: if i == index + size: return -1 index -= 1 #更新剩餘汽油量值 remainingGas += gas[index] - cost[index] #下一次檢查前,將兩個值歸0 remainingGas = 0 needGas = 0 #儲存非法出發點,區間(index, i]內的出發點都是非法的, #因為這些節點都不沒有足夠的汽油可以使用 unablePos.extend([(x + size) % size for x in range(i,index,-1)]) i += 1 #尋找合理出發點 pos = [[x,0] for x in range(size)] for i in unablePos: pos[i][1] = 1 for i in pos: if i[1] == 0: return i[0] return -1