Leetcode练习(Python):贪心算法类:第134题:加油站:在一条环路上有 N 个加油站,其中第 i 个加油站有汽油 gas[i] 升。 你有一辆油箱容量无限的的汽车,从第 i 个加油站开往第 i+1 个加油站需要消耗汽油 cost[i] 升。你从其中的一个加油站出发,开始时油箱为空。 如果你可以绕环路行驶一周,则返回出发时加油站的编号,否则返回 -1。
题目:
加油站:在一条环路上有 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
浙公网安备 33010602011771号