Java for LeetCode 134 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.

解题思路:

由于答案唯一,所以,只能按照一个方向走(不需要考虑从i+1→i的情况)

考虑到从i出发,到达i+j之后无法前进,那么从i+i出发,最多也只能到达i+j,所以下次循环可以从i+j+1开始,JAVA实现如下:

	public int canCompleteCircuit(int[] gas, int[] cost) {
		for (int i = 0; i < gas.length; i++) {
			int sum = gas[i] - cost[i];
			int index = i, count = 0;
			while (sum >= 0) {
				if (++count == gas.length)
					return index;
				int j = ++i % gas.length;
				sum += gas[j] - cost[j];
			}
		}
		return -1;
	}

 

posted @ 2015-06-02 10:44  TonyLuis  阅读(237)  评论(0编辑  收藏  举报