LeetCode题解: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.

题意:有N个汽油站围成环,gas[i]代表每个站的汽油量,cost[i]代表开车从第i个站到下一个站(i+1)消耗的汽油量。假设你从某一个汽油站出发,此时你的车汽油缸是空的(缸容量无限),求出你可以绕这个环一圈的汽油站索引,如果没有就返回-1。

思路:假如一辆车可以绕环一圈,必有:i:0->n-1,gas[i] - cost[i]的累和>=0。所以累和小于0就说明不能绕环一圈,则返回-1;假如累和大于等于0,此时我们需要求索引,那么怎么求索引呢?

假如我们能绕环一圈,说明存在以下两种情况的一种:

  1. 每一站的gas[i]-cost[i]>=0
  2. 有些站gas[i]-cost[i]<0,有些>=0

对于第一种情况,任意i都能作为索引返回。

第二种情况:假设在第i个站有gas[i]-cost[i]<0,此时我们选择i作为起点的话,无法到达下一站,因为汽油不够。因此,无论如何,我们必须选择第j个站,且第j个站最起码需要满足条件:

  1. j
public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int sum = 0;
        int total = 0;
        int start = -1;

        for(int i = 0; i < gas.length; i++){
            sum += gas[i] - cost[i];
            total += gas[i] - cost[i];

            if(sum < 0){
                start = i;
                sum = 0;
            }
        }

        if(total < 0){
            return -1;
        }else{
            return start + 1;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值