題目:
加油站:在一條環路上有 N 個加油站,其中第 i 個加油站有汽油 gas[i] 升。 你有一輛油箱容量無限的的汽車,從第 i 個加油站開往第 i+1 個加油站需要消耗汽油 cost[i] 升。你從其中的一個加油站出發,開始時油箱為空。 如果你可以繞環路行駛一周,則返回出發時加油站的編號,否則返回 -1。
說明:
- 如果題目有解,該答案即為唯一答案。
- 輸入數組均為非空數組,且長度相同。
- 輸入數組中的元素均為非負數。
思路:
首先尋找每個可以作為起點的站點,然后從這個站點開始進行判斷,是否滿足條件,如果滿足條件則返回對應的起點。
程序:
class Solution: def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: if not gas or not cost: return -1 if len(gas) != len(cost): return -1 if sum(gas) < sum(cost): return -1 auxiliary_for_start = [] for index in range(len(gas)): if gas[index] >= cost[index]: auxiliary_for_start.append(index) for start in auxiliary_for_start: gas_in_tank = 0 index1 = start findOut = True for index2 in range(len(gas)): gas_in_tank = gas_in_tank + gas[index1] - cost[index1] if gas_in_tank < 0: findOut = False break if index1 + 1 == len(gas): index1 = 0 else: index1 += 1 if findOut == True: return start return -1