每日一题134-加油站

1.题目详情

在一条环路上有 N 个加油站,其中第 i 个加油站有汽油 gas[i] 升。

你有一辆油箱容量无限的的汽车,从第 i 个加油站开往第 i+1 个加油站需要消耗汽油 cost[i] 升。你从其中的一个加油站出发,开始时油箱为空。

如果你可以绕环路行驶一周,则返回出发时加油站的编号,否则返回 -1。
在这里插入图片描述

2.解题思路

初始选择索引值时,要选择加油站的油要比消耗的油多,即gas[i] > cost[i]。转一周即跑一次列表的长度,每一次都需要判断油是否能支持下一次到加油站。

3.代码实现

这里是将列表延长了一倍,把圆环变成了直线

class Solution:
    def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
        l,r = 0,0
        cursor = 0
        arr = []
        while l < len(gas) and r < len(cost):# 将有可能的索引值都存到列表中
            if gas[l] >= cost[r]:
                cursor = l
                arr.append(cursor)
            l += 1
            r += 1
        for h in range(0, len(gas)): # 扩大列表长度,使圆环变成直线
            gas.append(gas[h])
        for q in range(0, len(cost)):
            cost.append(cost[q])
        for u in arr:
            x = 0
            xl, xr = u,u
            c = gas[xl]
            count = 0
            while count < len(gas) // 2: # 因为列表变长了一倍,但是转一周是原来列表的长度所以要整除2
                c = c - cost[xr] + gas[xl + 1]
                count += 1
                if xl < len(gas) - 2:
                    xl += 1
                xr += 1
                if c - cost[xr] < 0:
                    x = 1
                    break
            if x != 1:
                return u
        return -1

还是题解的简单

class Solution:
    def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
        if sum(gas)-sum(cost) < 0: return -1
        n = len(gas)
        start = oil = 0
        for i in range(n):
            if oil + gas[i] - cost[i] >= 0:
                oil += gas[i] - cost[i]
            else:
                start = i+1
                oil = 0
        return start

4.知识点

考虑问题要全面

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值