Skip to content

Commit cd5aea4

Browse files
committed
Time: 3 ms (35.74%), Space: 66 MB (41.74%) - LeetHub
source:d3bae561193393b9292f1f67f4a98cae5294d947
1 parent 2e5ccca commit cd5aea4

File tree

1 file changed

+20
-10
lines changed

1 file changed

+20
-10
lines changed

공예영/8주차/0134-gas-station/0134-gas-station.js

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,25 @@
44
* @return {number}
55
*/
66
var canCompleteCircuit = function(gas, cost) {
7-
let total = 0, current = 0, start = 0;
8-
for (let i = 0; i < gas.length; i++) {
9-
let diff = gas[i] - cost[i];
10-
total += diff;
11-
current += diff;
12-
if (current < 0) {
13-
start = i + 1;
14-
current = 0;
7+
// two pointers
8+
let start = 0;
9+
let end = 0;
10+
let sum = gas[start] - cost[start];
11+
const len = gas.length;
12+
13+
while(start < len){
14+
if(sum < 0){
15+
start = end+1;
16+
end = start;
17+
sum = gas[start] - cost[start];
18+
} else {
19+
if(end-start === len-1) return start;
20+
end++;
21+
let endIdx = end % len;
22+
sum += gas[endIdx]-cost[endIdx];
23+
}
24+
1525
}
16-
}
17-
return total >= 0 ? start : -1;
26+
return -1;
27+
1828
};

0 commit comments

Comments
 (0)