-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathGasStation.java
More file actions
72 lines (65 loc) · 1.44 KB
/
GasStation.java
File metadata and controls
72 lines (65 loc) · 1.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/**
*
*/
package cc.dectinc.leetcode;
/**
* @author chenshijiang
* @date Apr 13, 2015 2:54:17 PM
*
*/
public class GasStation {
public int canCompleteCircuit(int[] gas, int[] cost) {
if (gas == null || gas.length == 0) {
return -1;
}
int numStations = gas.length;
int tank = 0;
int start = 0;
for (int i = 0; i < 2 * numStations - 1; i++) {
int pos = i % numStations;
tank += gas[pos] - cost[pos];
if (tank < 0) {
start = i + 1;
if (start >= numStations) {
return -1;
}
tank = 0;
}
}
return start;
}
public int canCompleteCircuitNaive(int[] gas, int[] cost) {
if (gas == null || gas.length == 0) {
return -1;
}
int numStations = gas.length;
int[] residual = new int[numStations];
// calculate residual if start at Station 0
for (int i = 0; i < numStations; i++) {
residual[i] = gas[i] - cost[i];
}
// Roll start station
int start = 0;
while (start < numStations) {
int tank = residual[start];
int i = start;
while (tank >= 0 && i < numStations) {
tank += residual[i % numStations];
i++;
}
if (i == numStations) {
return start;
}
start++;
}
return -1;
}
public static void main(String[] args) {
GasStation sol = new GasStation();
int[] gas = new int[] { 2, 4 };
int[] cost = new int[] { 3, 4 };
// int[] gas = new int[] { 0, 5 };
// int[] cost = new int[] { 2, 3 };
System.out.println(sol.canCompleteCircuit(gas, cost));
}
}