Skip to content

Commit 2fdf4f6

Browse files
committed
add solution of problem 134: gas station
1 parent 68ba5b5 commit 2fdf4f6

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

GasStation134/README.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
There are *N* gas stations along a circular route, where the amount of gas at station *i* is `gas[i]`.
2+
3+
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.
4+
5+
Return the starting gas station's index if you can travel around the circuit once, otherwise return -1.
6+
7+
#####Note:
8+
The solution is guaranteed to be unique.

GasStation134/Solution.java

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
public class Solution {
2+
public int canCompleteCircuit(int[] gas, int[] cost) {
3+
if (gas == null || cost == null || gas.length != cost.length)
4+
return -1;
5+
6+
int[] gasLeft = new int[gas.length];
7+
8+
for (int i = 0; i < gas.length;) {
9+
int j = 0;
10+
if (gas[i] >= cost[i]) {
11+
int remainGas = 0;
12+
for (; j < gas.length && remainGas >= 0; j++) {
13+
int idx = (i + j) % gas.length;
14+
remainGas += gas[idx] - cost[idx];
15+
}
16+
if (j == gas.length && remainGas >= 0)
17+
return i;
18+
}
19+
20+
if (j > 0)
21+
i += j;
22+
else
23+
i++;
24+
}
25+
26+
return -1;
27+
}
28+
}

0 commit comments

Comments
 (0)