leetcode Gas Station

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.

解析:

1 计算空车从某个station出发,到达下一个station的gasLeft。

2 以某个station为起点进行遍历。

3 计算从起点到达每个station的gasLeft,如果有负值,则不符合条件。

4 想不到竟然Accept了。

代码如下:

 1     private boolean canCompleteCircuit(int[] gasLeft, int startStation) {

 2         int gas = 0;

 3         int currentStation = startStation;

 4         while(true) {

 5             gas += gasLeft[currentStation];

 6             if (gas < 0) {

 7                 return false;

 8             }

 9             currentStation ++;

10             if (currentStation == gasLeft.length) { currentStation = 0; }

11             if (currentStation == startStation) { break; }

12         }

13         return true;

14     }

15     public int canCompleteCircuit(int[] gas, int[] cost) {

16         int[] gasLeft = new int[gas.length];

17         for (int i = 0; i < cost.length; i++) {

18             gasLeft[i] = gas[i] - cost[i];

19         }

20         for (int i = 0; i < gasLeft.length; i++) {

21             if (gasLeft[i] >= 0 && canCompleteCircuit(gasLeft, i)) {

22                 return i;

23             }

24         }

25         return -1;

26     }
View Code

原本以为会超时。

其实最开始想到的是,汽车可以选择方向。先判断可能travel around的方向,再进行遍历。

这题看起来会有更好解法,请留言。

 

你可能感兴趣的:(LeetCode)