题目描述:
题解:
1.在一个for中对每个位置进行一次判断,如果满足环形行驶一周,则返回该位置编号,如果每个位置都不满足,则返回-1
2.对每个位置i进行判断时,total_gas记录总优量,初始为gas[i]-cost[i],开始向下环形行驶(j从1到总长度,下一个位置station_number由(i+j)%总长确定),total_gas更新为total_gas=total_gas+gas[station_number]-cost[station_number],如果所有情况下的total_gas>0,则返回i。所有i均不满足,则返回-1
3.需要注意:total_gas所有时刻大于0才满足,如果只有一个加油站,当其gas>cost时可以完成环形行驶。
class Solution(object): def canCompleteCircuit(self, gas, cost): number = len(gas) if number==1: if gas[0]>=cost[0]: return 0 else: return -1 for i in range(number): flag = 0 total_gas = gas[i]-cost[i] if total_gas<0: flag=1 for j in range(1,number+1): station_number = (i+j)%number total_gas = total_gas + gas[station_number] total_gas = total_gas - cost[station_number] if total_gas<0: flag = 1 if total_gas>0 and flag==0: return i return -1
贪心解法:
https://www.jianshu.com/p/60878bbf2c36
思路:
如果从i出发无法实现环绕,则将start设为i+1,如果从i+1出发可以到达终点,则从i+1出发可以完成环形。