Skip to content

Commit 174581c

Browse files
Merge pull request youngyangyang04#731 from martisss/master
增加134.加油站 js解法
2 parents cc2f41c + 3c46136 commit 174581c

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

problems/0134.加油站.md

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -281,6 +281,48 @@ func canCompleteCircuit(gas []int, cost []int) int {
281281
```
282282

283283
Javascript:
284+
暴力:
285+
```js
286+
var canCompleteCircuit = function(gas, cost) {
287+
for(let i = 0; i < cost.length; i++) {
288+
let rest = gas[i] - cost[i] //记录剩余油量
289+
// 以i为起点行驶一圈,index为下一个目的地
290+
let index = (i + 1) % cost.length
291+
while(rest > 0 && index !== i) {
292+
rest += gas[index] - cost[index]
293+
index = (index + 1) % cost.length
294+
}
295+
if(rest >= 0 && index === i) return i
296+
}
297+
return -1
298+
};
299+
```
300+
解法一:
301+
```js
302+
var canCompleteCircuit = function(gas, cost) {
303+
let curSum = 0
304+
let min = Infinity
305+
for(let i = 0; i < gas.length; i++) {
306+
let rest = gas[i] - cost[i]
307+
curSum += rest
308+
if(curSum < min) {
309+
min = curSum
310+
}
311+
}
312+
if(curSum < 0) return -1 //1.总油量 小于 总消耗量
313+
if(min >= 0) return 0 //2. 说明油箱里油没断过
314+
//3. 从后向前,看哪个节点能这个负数填平,能把这个负数填平的节点就是出发节点
315+
for(let i = gas.length -1; i >= 0; i--) {
316+
let rest = gas[i] - cost[i]
317+
min += rest
318+
if(min >= 0) {
319+
return i
320+
}
321+
}
322+
return -1
323+
}
324+
```
325+
解法二:
284326
```Javascript
285327
var canCompleteCircuit = function(gas, cost) {
286328
const gasLen = gas.length

0 commit comments

Comments
 (0)