leetcode 134. Gas Station

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.
环形公路加油站问题。一条环形公路上有N个加油站,加油站i的油量为gas[i],从加油站i到i+1的耗油为cost[i]。汽车的油箱容量不限。求从哪个站点出发可以跑完全程,不存在则返回-1。

Note:
The solution is guaranteed to be unique.

2、分析

gas[i]-cost[i]等于从i到i+1还剩的油量。
int current 记录当前剩油量
int total 记录总剩油量
从0站点开始遍历:
对每站gas[i]-cost[i]求和。current+=gas[i]-cost[i],total+=gas[i]-cost[i]
如果累计剩油量current<0,则0-i的所有站点都不可能作为出发点。(因为跑不到下一站就没油了)。把i+1设置为新出发点,current重置。

遍历结束后:如果total<0,说明总体是跑不到的,返回-1;否则返回找到的起始点。

3、代码

int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
    int total = 0;//总剩油量
    int current = 0;//当前剩油量
    int start = 0;
    for (int i = 0; i < gas.size(); i++) {
        current += gas[i] - cost[i];
        total += gas[i] - cost[i];
        if (current < 0)//i和之前的所有站点不能成为起始点
        {
            start = i + 1;
            current = 0;
        }
    }
    return total < 0 ? -1 : start;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值