134. Gas Station | Java最短代码实现

原题链接: 134. Gas Station

【思路1】

从末站开始,startStation和endStation均指向最后一站,一旦发现剩余的油量小于0,那么startStation前移——回去“加油”,直到油量大于等于0,那么endStation开始后移——继续前进。如果最后的剩余油量大于等于0,那么表示可以环游一周,startStation即为解。否则,不可以,返回 -1。

    public int canCompleteCircuit(int[] gas, int[] cost) {
        int startStation = gas.length - 1, endStation = gas.length - 1;
        int travelCount = 0;
        int totalRemain = 0, remain = gas[startStation] - cost[startStation];
        while (travelCount++ < gas.length) {
            totalRemain += remain;
            if (totalRemain < 0 && --startStation >= 0) {
                remain = gas[startStation] - cost[startStation];
            } else {
                endStation++;
                remain = gas[endStation % gas.length] - cost[endStation % gas.length];
            }
        }
        return totalRemain >= 0 ? startStation : -1;
    }
16 / 16  test cases passed. Runtime: 1 ms  Your runtime beats 7.59% of javasubmissions.
【思路2】

假设startStation = 0,往后开,假设在第 i 站第一次总油量小于0,那么表示 0 至第 i - 1 站均不适合作为起始站,此时总剩余油量 remain1 < 0。那么将第 i 站作为起始站,同样的,一旦发现油量 remain2 < 0,那么就重设起始站。最后遍历完gas之后,如果 totalRemain >= 0,那么startStation就是起始站,并且[startStation, gas.length - 1]必然remain均大于0:

    public int canCompleteCircuit(int[] gas, int[] cost) {
        int startStation = 0, totalRemain = 0, remain = 0;
        for (int i = 0; i < gas.length; i++) {
            totalRemain += gas[i] - cost[i];
            if (remain < 0) {
                remain = gas[i] - cost[i];
                startStation = i;
            } else {
                remain += gas[i] - cost[i];
            }
        }
        return totalRemain >= 0 ? startStation : -1;
    }
欢迎优化!

你可能感兴趣的:(134. Gas Station | Java最短代码实现)