[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.
思路
这道题最明显的是O(n^2)的算法,就是对每个点能否到达终点进行模拟。
还有一个O(n)的算法。代码如下,这种解法充分利用了题中只有一个唯一解(如果有解的话)的信息。思考一下:
1.如果total<0则一定没有解,因为不管从哪个位置开始,一定无法通过最后一个加油站。
1.如果total>=0一定有解,而且这个解一定是最后一个sum<0的下一个位置(j=i+1)。读者可以仔细思考一下为什么(tips:假设有k个sum<0的点,结合其他信息推断只有该点是有效起始位置)。
代码
public int canCompleteCircuit(int[] gas, int[] cost) { // Note: The Solution object is instantiated only once and is reused by each test case. int n=gas.length; if(n==0) return -1; int sum=0,total=0; int j=0; for(int i=0;i<n;i++) { sum+=(gas[i]-cost[i]); total+=(gas[i]-cost[i]); if(sum<0) { j=i+1; sum=0; } } return total>=0?j:-1; }