题解 | #加油站#

加油站

http://www.nowcoder.com/practice/a013a0691a0343aeb262ca1450d2fe4e

双指针
有油时候前指针可以前进(烧油),没油时候后指针必须后退(取油),直到两指针碰上。
如果最终油量大于0,可以跑足一圈,否则不能。
class Solution:
    def gasStation(self , gas: List[int], cost: List[int]) -> int:
        # write code here
        sta,end=0,len(gas)-1
        theg=0
        while sta<=end:
            if theg<0:
                theg+=gas[end]-cost[end]
                end+=-1
            else:
                theg+=gas[sta]-cost[sta]
                sta+=1
        if theg>=0:
            return sta
        else:
            return -1

全部评论

相关推荐

05-21 15:47
门头沟学院 Java
浪漫主义的虹夏:项目有亮点吗,第一个不是纯玩具项目吗,项目亮点里类似ThreadLocal,Redis储存说难听点是花几十分钟绝大部分人都能学会,第二个轮子项目也没体现出设计和技术,想实习先沉淀,好高骛远的自嗨只会害了自己
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务