[LeetCode] Gas Station

本文探讨了一个经典的加油站问题:在一个环形路线上有n个加油站,每个加油站提供一定量的汽油,同时从一个加油站到下一个加油站需要消耗一定的汽油。任务是找到一个起点,使得汽车能够从该起点出发并绕完整个环形路线回到起点。文章提供了详细的解决方案,并通过代码实现验证了这一方法的有效性。

 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. 


加油站问题,有n个加油站,在一个环形上,从一个加油站到另一个加油站需要cost[i]的油量,加油站中有gas[i]的油量,问是否能够从一个加油站出发,绕一圈,可以的话返回出发的加油站,不可以的话返回-1

我们来证明:若油站的总油量大于等于路途的总消耗,那么一定可以走完一圈。

从加油站i 经过加油站j 到达加油站k等价于将j的油量全部放到i,然后从i走到k,如此等价,可以证明走一圈其实就等价于所有油量减去所有消耗


如何找这个出发点?假设车子开始有无限多的油,从任意一个加油站出发,走一圈,记录在每一个加油站的剩余油量,剩余油量最小的加油站,就是要出发的加油站。

class Solution {
public:
    int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        int totalGas = 0;
        int totalCost = 0;
        for(int i = 0; i < gas.size(); i++) {
            totalGas += gas[i];
        }
        for(int i = 0; i < cost.size(); i++) {
            totalCost += cost[i];
        }
        if(totalGas < totalCost)  return -1;
        
        int minPos = 0;
        int startGas = INT_MAX - (totalGas);
        int index = 0;
        int minRemain = INT_MAX;
        while(index < gas.size()) {
            if(startGas < minRemain) {
                minPos = index;
                minRemain = startGas;
            }
            startGas = startGas + gas[index] - cost[index];
            index++;
        }
        
        return minPos;
        
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值