File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change @@ -281,6 +281,48 @@ func canCompleteCircuit(gas []int, cost []int) int {
281
281
```
282
282
283
283
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
+ 解法二:
284
326
``` Javascript
285
327
var canCompleteCircuit = function (gas , cost ) {
286
328
const gasLen = gas .length
You can’t perform that action at this time.
0 commit comments