-
Notifications
You must be signed in to change notification settings - Fork 0
/
gas-station.js
45 lines (38 loc) · 982 Bytes
/
gas-station.js
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
/**
* 134. 加油站
* @param {number[]} gas
* @param {number[]} cost
* @return {number}
*/
var canCompleteCircuit = function (gas, cost) {
// 暴力方法
for (let i = 0; i < gas.length; i++) {
let restGas = gas[i] - cost[i]; // 记录剩余油量
let index = (i + 1) % gas.length;
while (restGas > 0 && index !== i) {
// 模拟以 i 为起点行驶一周
restGas += gas[index] - cost[index];
index = (index + 1) % gas.length;
}
// 如果以 i 为起点跑一圈, 剩余油量 >= 0, 返回该起始位置
if (restGas >= 0 && index === i) {
return i;
}
}
return -1;
};
// 贪心方法
var canCompleteCircuit2 = function (gas, cost) {
let start = 0;
let totalSum = 0;
let currSum = 0;
for (let i = 0; i < gas.length; i++) {
currSum += gas[i] - cost[i];
totalSum += gas[i] - cost[i];
if (currSum < 0) {
start = i + 1;
currSum = 0;
}
}
return totalSum < 0 ? -1 : start;
};