Leetcode-Gas Station(Java)

Question:

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.

Thinking:

Nomally, it can be sovled in n^2 time complexity, check every station whether it is possible. But it will be LTE, so we need a greedy method to sovle this problem. In fact, if previous result of total gas is larger than 0, and current gas station don’t meet the needs, it means all of the previous gas station is not valid. What’s more, it assumes there is only one solution, so what we need to do is to record the fisrt valid station index. In order to check whether it is valid, we also need another variable total to determine whether the set is valid.

Solution1:(LTM)

public int canCompleteCircuit1(int[] gas, int[] cost) {
    int len = gas.length;

    for (int i = 0; i < len; i++){
        int curGas = 0;
        for (int j = i; ; j++){
            curGas += gas[j%len];
            curGas -= cost[j%len];
            if (curGas < 0)
                break;
            if (j - len == i - 1){
                return i;
            }
        }
    }

    return -1;
}

Solution2:(Greedy)

public int canCompleteCircuit(int[] gas, int[] cost) {
    int len = gas.length;
    int curSum = 0;
    int total = 0;
    int index = 0;

    for (int i = 0; i < len; i++){
        curSum += gas[i] - cost[i];
        total += gas[i] - cost[i];
        if (curSum < 0){
            curSum = 0;
            index = i + 1;
        }
    }
    if (total < 0)
        return -1;
    else
        return index;

}