[LeetCode] Gas Station

来源:互联网 发布:铁拳3知乎 编辑:程序博客网 时间:2024/05/16 11:02

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.

使用贪心算法。规律是,如果从某个加油站出发,如果可以到达的最远终点不是自身,那么从这个加油站到其最远终点之间的所有加油站都可以排除,直接以上一轮的终点为起点再开始考虑。因为如果以中途加油站为起点考虑,那样会损失从之前加油站来的时候余下的油的优势,就更不可能最后到达自身了。

如果这样一直考虑,最后终点过了最原始起点,说明所有的点都被考虑过了一遍。时间复杂度O(N)。

public int canCompleteCircuit(int[] gas, int[] cost) {int length = gas.length;int start;int k = 0; // start testing from the first stationwhile (true) {int sum = 0;start = k % length; // save the starting pointdo {sum += gas[k % length] - cost[k % length];k++;} while (sum >= 0 && k < start + length);// complete a cycleif (k == start + length && sum >= 0) {return k - length;}// test from the end that has not been reachedelse {if (k >= length)return -1;}}}


原创粉丝点击