Skip to content

Commit ad73e34

Browse files
committed
134. 加油站
1 parent f5697a8 commit ad73e34

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,7 @@
8383
|125|[验证回文串](https://leetcode.cn/problems/valid-palindrome/)|[JavaScript](./algorithms/valid-palindrome.js)|Easy|
8484
|129|[求根节点到叶节点数字之和](https://leetcode.cn/problems/sum-root-to-leaf-numbers/)|[JavaScript](./algorithms/sum-root-to-leaf-numbers.js)|Medium|
8585
|131|[分割回文串](https://leetcode.cn/problems/palindrome-partitioning/)|[JavaScript](./algorithms/palindrome-partitioning.js)|Medium|
86+
|134|[加油站](https://leetcode.cn/problems/gas-station/)|[JavaScript](./algorithms/gas-station.js)|Medium|
8687
|136|[只出现一次的数字](https://leetcode-cn.com/problems/single-number/)|[JavaScript](./algorithms/single-number.js)|Easy|
8788
|141|[环形链表](https://leetcode-cn.com/problems/linked-list-cycle/)|[JavaScript](./algorithms/linked-list-cycle.js)|Easy|
8889
|142|[环形链表 II](https://leetcode.cn/problems/linked-list-cycle-ii/)|[JavaScript](./algorithms/linked-list-cycle-ii.js)|Medium|

algorithms/gas-station.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* 134. 加油站
3+
* @param {number[]} gas
4+
* @param {number[]} cost
5+
* @return {number}
6+
*/
7+
var canCompleteCircuit = function (gas, cost) {
8+
// 暴力方法
9+
10+
for (let i = 0; i < gas.length; i++) {
11+
let restGas = gas[i] - cost[i]; // 记录剩余油量
12+
let index = (i + 1) % gas.length;
13+
14+
while (restGas > 0 && index !== i) {
15+
// 模拟以 i 为起点行驶一周
16+
restGas += gas[index] - cost[index];
17+
index = (index + 1) % gas.length;
18+
}
19+
// 如果以 i 为起点跑一圈, 剩余油量 >= 0, 返回该起始位置
20+
if (restGas >= 0 && index === i) {
21+
return i;
22+
}
23+
}
24+
25+
return -1;
26+
};
27+
28+
// 贪心方法
29+
var canCompleteCircuit2 = function (gas, cost) {
30+
let start = 0;
31+
let totalSum = 0;
32+
let currSum = 0;
33+
34+
for (let i = 0; i < gas.length; i++) {
35+
currSum += gas[i] - cost[i];
36+
totalSum += gas[i] - cost[i];
37+
38+
if (currSum < 0) {
39+
start = i + 1;
40+
currSum = 0;
41+
}
42+
}
43+
44+
return totalSum < 0 ? -1 : start;
45+
};

0 commit comments

Comments
 (0)