leetcode-Gas Station

本文介绍了一种解决循环线路上加油站问题的方法。该问题要求找到一个起点,使得汽车能通过加油站提供的油量完成整个环路的行驶。文章详细阐述了算法思路,并提供了具体的C++实现代码。

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

Gas Station

  Total Accepted: 12195  Total Submissions: 50108 My Submissions

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.

Have you been asked this question in an interview? 


汽车加油站:循环线路上有N个加油站,每个加油站有油量为gas[i],汽车油桶容量无限,从油站i到下一站(i+1)要花费cost[i],汽车从某个油站出发,要求返回能够走完全部油站的起始油站位置(唯一),否则返回-1.

能够走完全部油站的话说明所有油站的油量加起来不小于走完全程要耗的油量,我们可以用一个left动态数组来保存一个油站加油后到下一个油站可以剩下的油量,left[i]表示汽车在油站i加油走到(i+1)站剩下的油量。很显然,如果汽车能够走完全程的话,起始点i必须满足left[i]>=0,否则汽车开不到下一站。所以,这样可以遍历left数组,找到起始点left[i]>=0,然后继续走下去到j,如果出现起始点到该站的left总和<0,说明要更新起始点。而中间的[i,j]站点全部都不能当做起始点,如果中间某个站k的left[k]>=0,从k出发是到不了j的。所以更新起始点到j后面的>=0的left。
class Solution {
public:
    int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
        vector<int> left;
        left.reserve(gas.size());
        int i;
        for (i=0; i<gas.size(); ++i) {
            left.push_back(gas[i] - cost[i]);
        }
        int idx(0), sum(0), subsum(0);
        for (i=0; i<left.size(); ++i) {
            if (subsum+left[i]>=0) {
                subsum += left[i];
            } else {
                subsum = 0;
                idx = i + 1;
            }
            sum += left[i];
        }
        if (sum < 0) return -1;
        return idx;
    }
}

关于STL vector使用技巧:一般来说,如果知道vector要容纳的元素数量,可以先调用reserve函数预先分配这么多的容量,容量大小可以通过capacity函数获得,size函数是获取容器当前容纳元素的数量。如果不先reserver,我们知道vector的内存分配是当容量不够时,要在另一块内存分配两倍大小的空间,然后把原来内存的元素拷贝过去,再释放原内存空间,这样分配、拷贝、释放内存当然没只分配一次内存效率高。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值