第八周的作业2--Leetcode 134. Gas Station

Leetcode 134. 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 in the clockwise direction, otherwise return -1.

解题思路:
  设一个站油箱里油数为之前站油箱的油数加上该站允许加的最大油数,减去该站驶向下一站需要开销的油数;
  假设从一个起始站开始顺序遍历,若每个站油箱的油数不为负数,则说明车从起始站能够正常驶向该站的下一站;否则说明起始站与当前站之间的所有站都无法满足条件,故从起始站置为当前站的下一站,又执行顺序判断。
  最后还需要判断从当前起始站驶向列表中的最后一站后,又驶向列表的第一站,然后从第一站驶向当前的起始站,是否能够保证正常的行驶。

class Solution:
    def canCompleteCircuit(self, gas, cost):
        """
        :type gas: List[int]
        :type cost: List[int]
        :rtype: int
        """
        ans = 0 # 可以走完一圈的起始站下标
        tank = 0 # 邮箱的油

        for i in range(0, len(gas)):
            tank += gas[i] - cost[i]
            if tank < 0:
                '''如果该站油箱的油数为负数,说明从当前起始站到该站之间的所有站点都不满足条件'''
                tank = 0
                ans = i + 1 # 将起始站下标设置该站的下一个站

        if ans == len(gas): # 如果一遍循环之后,起始站值已经被设为超界了,则不存在满足条件的站
            return -1

        for i in range(0, ans): # 否则还需要遍历从0站点到当前起始站的之间的所有站点,才能构成一个圈
            tank += gas[i] - cost[i]
            if tank < 0:
                return -1

        return ans

效率分析:
  显然该算法的时间复杂度为O(n),效率还是比较好的。
这里写图片描述

猜你喜欢

转载自blog.csdn.net/m0_37600543/article/details/80160488
今日推荐