Leetcode 每日一题——134. 加油站

134. 加油站

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

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

如果你可以绕环路行驶一周,则返回出发时加油站的编号,否则返回 -1。

**说明: **

  1. 如果题目有解,该答案即为唯一答案。
  2. 输入数组均为非空数组,且长度相同。
  3. 输入数组中的元素均为非负数。
    在这里插入图片描述
    该题的解题思路是筛选去除不可能是起点的加油站,C++代码如下:
class Solution {
public:
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
        int currentStation=0;
        int totalGas=0;
        int curentTank=0;
        for(int i=0;i<gas.size();i++)
        {
            totalGas+=gas[i]-cost[i];
            curentTank+=gas[i]-cost[i];
            if(curentTank<0)
            {
                curentTank=0;
                currentStation=i+1;
            }
        }
        return totalGas>=0? currentStation:-1;
    }
};

运行效果:
在这里插入图片描述
相同思路Python代码如下:

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

运行效果:
在这里插入图片描述

来源:力扣(LeetCode)链接:https://leetcode-cn.com/problems/gas-station

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值