leetcode python3 加油站

代码思路:采用双指针遍历方法,首先判断总油量是否大于总耗油量,是则必能完成行驶人物,反之无法完成,若可以,开始遍历,初始化车的起点指针i,若该点的油量不足,则起点指针右移,若油量可以行驶至下一站点,则初始行驶指针j,开始判断行驶下一站点后油量是否可以继续行驶,若不可以则令起点指针i等于行驶指针j,直至完成循环

class Solution:
    def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
        if sum(gas)<sum(cost):return -1
        i=0
        while i<len(gas):
            flag=0         
            gasCurr=0
            if gas[i]-cost[i]<0:
                i+=1 continue
            gasCurr=gas[i]-cost[i]
            j=i+1
            if j>len(gas)-1:j=0;
            while j!=i:                
                gasCurr=gasCurr+gas[j]-cost[j]
                if gasCurr<0:
                    i,flag=j,1
                    break
                else:
                    j+=1
                    if j>len(gas)-1:j=0;
                    continue
            if flag==0:return i
发布了30 篇原创文章 · 获赞 0 · 访问量 301

猜你喜欢

转载自blog.csdn.net/m0_37656366/article/details/105173273