码迷,mamicode.com
首页 > 其他好文 > 详细

Gas Station

时间:2015-04-12 06:33:18      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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)。这个。。。不大好。其实我们重复计算了很多。

比如,我们以 a 为起点,试图走 a + 1, a + 2,a + 3 ... 一直走到b。如果我们在计算过程中发现,a 根本到不了b。按照原来的方法,我们该以 a + 1为起点,再算一次看能不能到b。

想想是不可能的。如果从a出发, 到a + 1点后,邮箱里有从a剩下的油(最不济刚好为空)。带着剩下的油都到不了b,你空着邮箱从头开始怎么可能。所以起点肯定不在a到b这段了。直接从b + 1开始算。

 1 public int canCompleteCircuit(int[] gas, int[] cost) {
 2         if (gas == null || cost == null || gas.length == 0 || cost.length == 0) {
 3             return -1;
 4         }
 5         int start = 0;
 6         int tank = 0;
 7         int sum = 0;
 8         for (int j = 0; j < gas.length; j++) {
 9             int diff = gas[j] - cost[j];
10             if (tank + diff >= 0) {
11                 tank += diff; 
12             }else{
13                 start = j + 1;
14             }
15         }
16         for (int i = 0; i < gas.length; i++) {
17             sum = sum + gas[i] - cost[i];
18         }
19         if (sum >= 0) {
20             return start;
21         }else{
22             return -1;
23         }
24     }

 

Gas Station

标签:

原文地址:http://www.cnblogs.com/gonuts/p/4418876.html

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