[leedcode 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.

public class Solution {
    /*我们从0开始以其为起点实验,累加 restGas += gas[i] - cost[i],一旦在 i 处遇到restGas<0,那么就说明当前选择的起点beg不行,
    需要重新选择,此时我们不应该回去使用 beg+1 作为新起点,因为在beg处,一定有 gas>=cost,
    说明 beg+1 到 i 处的总gas一定小于总的cost,选择其中任何一个作为起点还是不行的,所以应该跳过这些点,
    以 i+1 作为新起点,遍历到 size-1 处就可以结束了,如果找到了可能的起点,我们还要进行验证,走一遍(total),
    如果没问题那么说明可以。*/

/*其实本质就是:这个起点将路径分为前后两段,前段总的余量为负,即油不够用,要想有解,那么后段油量应该为正,此时才可能有解,我们要做的就是找到这个分割点作为起点,然后再验证一下;反之,如果前段就为正了,那么显然可以直接选择前面的点为起点;如果整段加起来都是负的,那么无解。*/
    public int canCompleteCircuit(int[] gas, int[] cost) {
        
        int i=0;
        int left=0;
        int beg=0;
        int total=0;
        while(i<gas.length){
            left+=gas[i]-cost[i];
            total+=gas[i]-cost[i];//total为了验证整个数组是否gas>cost
            if(left<0){
                beg=i+1;
                left=0;
            }
            i++;
        }
        if(total>=0) return beg;
        else return -1;
    }
}
原文地址:https://www.cnblogs.com/qiaomu/p/4678055.html