leetcode @python 134. Gas Station
题目链接
https://leetcode.com/problems/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.
题目大意
在一条回路上,有n个加油站,每个加油站的油量为gas[i],从油站i到油站i+1的耗油量为cost[i],给定gas数组和cost数组,返回能够可以环绕这条回路的油站的索引,若不能环绕,则返回-1
解题思路
- 若总的油量小于总的cost,则肯定不能环绕
- 假设当前剩余的油量为sumcost,若达到站点i的的剩余油量小于0,则将设置起始站点设为i;另外设置所有站点的剩余油量为total,当total小于0,则不能环绕,否则可以
代码
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
sumcost = 0
total = 0
min_idx = 0
for i in range(len(gas)):
total += gas[i] - cost[i]
if gas[i] + sumcost < cost[i]:
min_idx = i + 1
sumcost = 0
else:
sumcost += gas[i] - cost[i]
if total >= 0:
return min_idx
else:
return -1