Skip to content

Commit 106461d

Browse files
committed
finish 134
1 parent 522a525 commit 106461d

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

134. Gas Station.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* 134. Gas Station
3+
*
4+
* There are N gas stations along a circular route, where the amount of gas at station i is gas[i].
5+
*
6+
* 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.
7+
*
8+
* Return the starting gas station's index if you can travel around the circuit once, otherwise return -1.
9+
*
10+
* Note:
11+
* The solution is guaranteed to be unique.
12+
*/
13+
14+
/**
15+
* @param {number[]} gas
16+
* @param {number[]} cost
17+
* @return {number}
18+
*/
19+
var canCompleteCircuit = function(gas, cost) {
20+
var len = gas.length;
21+
var tank = 0;
22+
var total = 0;
23+
var start = 0;
24+
for (var i = 0; i < len; i++) {
25+
tank += gas[i] - cost[i];
26+
if (tank < 0) {
27+
start = i + 1;
28+
total += tank;
29+
tank = 0;
30+
}
31+
}
32+
return tank + total >= 0 ? start : -1;
33+
};
34+
35+
// n 点到不了 m 点,则其间所有点都到不了 m 点
36+
// 总和大于等于 0 说明有解

0 commit comments

Comments
 (0)