Gas Station——LeetCode

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.

题意大概是:有N个加油站围成一个圈,每个加油站的油量是gas[i],从第i个加油站开到第i+1个加油站需要耗费cost[i]油量,问是否有一个解使得从某个加油站开始跑一圈,有的话返回开始跑的加油站的index。

我的做法就是从0开始遍历,sum+=gas[i]-cost[i],一旦sum<0了,说明从当前到0的所有点都不可能了,然后从下一个开始,一旦跑完一圈发现sum都不小于0,那么就可以返回当前的index了,否则全部遍历一遍没有解就返回-1。

Talk is cheap>>

  public int canCompleteCircuit(int[] gas, int[] cost) {

        int res;

        for (int i = 0; i < gas.length; i++) {

            res = gas[i] - cost[i];

            if (res >= 0) {

                int pos = i;

                for (int j = pos + 1; j < gas.length + pos; j++) {

                    int index = j % gas.length;

                    res += gas[index] - cost[index];

                    if (res < 0) {

                        pos = -1;

                        i = j;

                        break;

                    }

                }

                if (pos >= 0)

                    return pos;

            }

        }

        return -1;

    }

 

你可能感兴趣的:(LeetCode)