134. Gas Station

本文探讨了一道经典的算法问题——环路加油站问题。该问题要求找出一条环形路径上能够完成一次完整旅行的起始加油站。通过逆向思维,从最后一个节点开始检查,确保油箱余额始终非负,从而高效地找到了解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. 问题描述
    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.

  2. 解决思路
    其实就是找到从哪个点开始遍历,和一直不为负数。这里有一个问题就是只能够正向走,即i 只能走向i+1。所以我们可以假定从最后一个节点开始走,如果和为正,就正向走,如果和为负数,则将开始节点倒退,一直倒退到和为正位置。则最后倒退到不能倒退的节点就是我们要找的目标节点,如果最后得和还是负数,则不存在这样的节点。

  3. 代码

class Solution {
public:
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
        int n = gas.size();
        if (n == 1) {
            if (gas[0] >= cost[0])
                return 0;
            else
                return -1;
        }
        int end = n - 1, start = 0;
        int sum = gas[end]-cost[end];
        while(end > start) {
            if (sum > 0) {
                sum += gas[start]-cost[start];
                ++start;
            } else {
                --end;
                sum += gas[end]-cost[end];
            }
        }
        return sum >= 0 ? end:-1;
    }

};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值