134. Gas Station(补上周)

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.

Subscribe to see which companies asked this question.

这题的意思就是求出从哪一个油站开始,能走完整个里程,并且这个结果是唯一的;

首先我们可以得到所有油站的油量totalGas,以及总里程需要消耗的油量totalCost,如果totalCost大于

totalGas,那么铁定不能够走完整个里程;

如果totalGas大于totalCost了,那么就能走完整个里程了,假设现在我们到达了第i个油站,这时候还剩余

的油量为sum,如果 sum + gas[i] - cost[i]小于0,我们无法走到下一个油站,所以起点一定不在第i个以及

之前的油站里面(都铁定走不到第i + 1号油站),起点只能在i + 1后者后面。



代码如下:

class Solution {
public:
    int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
        int sum = 0;
        int total = 0;
        int k = 0;
        for(int i = 0; i < (int)gas.size(); i++) {
            sum += gas[i] - cost[i];
            if(sum < 0) {
                k = i + 1;
                sum = 0;
            }
            total += gas[i] - cost[i];
        }
        if(total < 0) {
        return -1;
        } 
        else {
            return k;
        }
    }
};

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值