134. &55 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.

Note:
The solution is guaranteed to be unique.

解题思路:
  • 首先,能不能的问题:只要gas[i]的和 > cost[i]的和就一定可以跑一圈。

  • 寻找开始的位置。贪心:不行就从头开始~

start, current_sum, total_sum = 0, 0, 0
        for i in range(len(gas)):
            diff = gas[i] - cost[i]
            current_sum += diff
            total_sum += diff
            if current_sum < 0:
                start = i + 1          #放在这个位置很巧妙简直无敌了,这也算贪心吧,如果current_sum < 0 ,从前开始就不行了。
                current_sum = 0

        if total_sum >= 0:
            return start


        return -1

if __name__ == "__main__":
    print(Solution().canCompleteCircuit([1, 2, 3], [3, 2, 1]))
    print(Solution().canCompleteCircuit([1, 2, 3], [2, 2, 2]))
    print(Solution().canCompleteCircuit([1, 2, 3], [1, 2, 3]))
    print(Solution().canCompleteCircuit([1, 2, 3], [1, 2, 4]))


  • 结果
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,672评论 0 10
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 10,790评论 0 23
  • 清晨的闹钟准时在六点四十五分响起,我从昨夜的睡梦中惊醒,匆忙地关掉闹钟。照例要多睡个十几分钟的,让自己一点一点从慵...
    九月星辰阅读 181评论 1 1
  • 昨天是周五,本就三堂课,体育老师请假,所以连续上了四节课,感觉说话都无力了!几个调皮蛋昨天异常的躁动,两大...
    吴丹丹丹阅读 259评论 0 0
  • 再一次看科比的最后一战,我还是湿了眼眶。从此,NBA湖人再也没有你,你的离去带走了属于我的篮球梦,属于我的青春,曾...
    向磊24阅读 218评论 0 0

友情链接更多精彩内容