码迷,mamicode.com
首页 > 编程语言 > 详细

Java for LeetCode 134

时间:2015-06-02 12:51:39      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:

Gas Station Total Accepted: 39396 Total Submissions: 153479

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;
	}

 

Java for LeetCode 134

标签:

原文地址:http://www.cnblogs.com/tonyluis/p/4545784.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!