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.

Note:
The solution is guaranteed to be unique.

题目意思比较简单,一圈加油站,每个加油站的汽油是gas[],到下一个加油站的消耗是cost[]。给出gas[] cost[],算出从哪个加油站出发可以跑完一圈。

解法就是遍历每一个加油站,每次循环内分成两段,设i开始,到末尾结束,然后从0开始到i结束。依次累加,判断剩余油sum+ gas[]-cost[],若中间有为负数的,就失败。

public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
            int sum=0;
            boolean nextloop = false;
        for (int i = 0; i < cost.length; i++) {
            for (int j = i; j < cost.length; j++) {
                sum=sum+gas[j]-cost[j];
                if (sum<0) {
                    nextloop=false;
                    break;
                }else {
                    nextloop=true;
                }
            }
            if (nextloop) {
                for (int j = 0; j < i; j++) {
                    sum=sum+gas[j]-cost[j];
                    if (sum<0) {
                        nextloop=false;
                        break;
                    }
                }
            }
            if (sum>=0) {
                return i;
            }
            sum=0;
        }
        return -1;
    }
}
原文地址:https://www.cnblogs.com/birdhack/p/3956684.html