IT技术小屋

秋风秋雨,皆入我心

  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  38 随笔 :: 1 文章 :: 19 评论 :: 0 Trackbacks
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.

首先,这个题目要明确如果gas[0] + gas[1] + ... + gas[n] >= cost[0] + cost[1] + .. + cost[n],那么这个题目一定有解。因为,根据条件移项可得:
(gas[0] - cost[0]) + (gas[1] - cost[1]) + ... + (gas[n] - cost[n]) >= 0,由于最终结果大于等于零,因此一定可以通过加法交换律,得到一个序列,使得中间结果都为非负。因此可以将算法实现如下:
 1 public class GasStation {
 2     public int canCompleteCircuit(int[] gas, int[] cost) {
 3         int sum = 0, total = 0, len = gas.length, index = -1;
 4         for (int i = 0; i < len; i++) {
 5             sum += gas[i] - cost[i];
 6             total += gas[i] - cost[i];
 7             if (sum < 0) {
 8                 index = i;
 9                 sum = 0;
10             }
11         }
12         return total >= 0 ? index + 1 : -1;
13     }
14 }
posted on 2013-12-19 09:29 Meng Lee 阅读(358) 评论(1)  编辑  收藏 所属分类: Leetcode

评论

# re: [Leetcode] Gas Station 2014-01-25 09:56 SunnyYoona
(gas[0] - cost[0]) + (gas[1] - cost[1]) + ... + (gas[n] - cost[n]) >= 0
但是并不能保证每一个(gas[i] - cost[i])都大于0

有点疑惑。。。。  回复  更多评论
  


只有注册用户登录后才能发表评论。


网站导航: