1.题目详情
在一条环路上有 N 个加油站,其中第 i 个加油站有汽油 gas[i] 升。
你有一辆油箱容量无限的的汽车,从第 i 个加油站开往第 i+1 个加油站需要消耗汽油 cost[i] 升。你从其中的一个加油站出发,开始时油箱为空。
如果你可以绕环路行驶一周,则返回出发时加油站的编号,否则返回 -1。
2.解题思路
初始选择索引值时,要选择加油站的油要比消耗的油多,即gas[i] > cost[i]。转一周即跑一次列表的长度,每一次都需要判断油是否能支持下一次到加油站。
3.代码实现
这里是将列表延长了一倍,把圆环变成了直线
class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
l,r = 0,0
cursor = 0
arr = []
while l < len(gas) and r < len(cost):# 将有可能的索引值都存到列表中
if gas[l] >= cost[r]:
cursor = l
arr.append(cursor)
l += 1
r += 1
for h in range(0, len(gas)): # 扩大列表长度,使圆环变成直线
gas.append(gas[h])
for q in range(0, len(cost)):
cost.append(cost[q])
for u in arr:
x = 0
xl, xr = u,u
c = gas[xl]
count = 0
while count < len(gas) // 2: # 因为列表变长了一倍,但是转一周是原来列表的长度所以要整除2
c = c - cost[xr] + gas[xl + 1]
count += 1
if xl < len(gas) - 2:
xl += 1
xr += 1
if c - cost[xr] < 0:
x = 1
break
if x != 1:
return u
return -1
还是题解的简单
class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
if sum(gas)-sum(cost) < 0: return -1
n = len(gas)
start = oil = 0
for i in range(n):
if oil + gas[i] - cost[i] >= 0:
oil += gas[i] - cost[i]
else:
start = i+1
oil = 0
return start
4.知识点
考虑问题要全面