File tree Expand file tree Collapse file tree 2 files changed +46
-0
lines changed Expand file tree Collapse file tree 2 files changed +46
-0
lines changed Original file line number Diff line number Diff line change 83
83
| 125| [ 验证回文串] ( https://leetcode.cn/problems/valid-palindrome/ ) | [ JavaScript] ( ./algorithms/valid-palindrome.js ) | Easy|
84
84
| 129| [ 求根节点到叶节点数字之和] ( https://leetcode.cn/problems/sum-root-to-leaf-numbers/ ) | [ JavaScript] ( ./algorithms/sum-root-to-leaf-numbers.js ) | Medium|
85
85
| 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|
86
87
| 136| [ 只出现一次的数字] ( https://leetcode-cn.com/problems/single-number/ ) | [ JavaScript] ( ./algorithms/single-number.js ) | Easy|
87
88
| 141| [ 环形链表] ( https://leetcode-cn.com/problems/linked-list-cycle/ ) | [ JavaScript] ( ./algorithms/linked-list-cycle.js ) | Easy|
88
89
| 142| [ 环形链表 II] ( https://leetcode.cn/problems/linked-list-cycle-ii/ ) | [ JavaScript] ( ./algorithms/linked-list-cycle-ii.js ) | Medium|
Original file line number Diff line number Diff line change
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
+ } ;
You can’t perform that action at this time.
0 commit comments