Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 1da68a3

Browse files
committed
添加 0134.加油站.md Scala版本
1 parent 882c19c commit 1da68a3

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

‎problems/0134.加油站.md

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -471,5 +471,73 @@ int canCompleteCircuit(int* gas, int gasSize, int* cost, int costSize){
471471
}
472472
```
473473

474+
### Scala
475+
476+
暴力解法:
477+
478+
```scala
479+
object Solution {
480+
def canCompleteCircuit(gas: Array[Int], cost: Array[Int]): Int = {
481+
for (i <- cost.indices) {
482+
var rest = gas(i) - cost(i)
483+
var index = (i + 1) % cost.length // index为i的下一个节点
484+
while (rest > 0 && i != index) {
485+
rest += (gas(index) - cost(index))
486+
index = (index + 1) % cost.length
487+
}
488+
if (rest >= 0 && index == i) return i
489+
}
490+
-1
491+
}
492+
}
493+
```
494+
495+
贪心算法,方法一:
496+
497+
```scala
498+
object Solution {
499+
def canCompleteCircuit(gas: Array[Int], cost: Array[Int]): Int = {
500+
var curSum = 0
501+
var min = Int.MaxValue
502+
for (i <- gas.indices) {
503+
var rest = gas(i) - cost(i)
504+
curSum += rest
505+
min = math.min(min, curSum)
506+
}
507+
if (curSum < 0) return -1 // 情况1: gas的总和小于cost的总和,不可能到达终点
508+
if (min >= 0) return 0 // 情况2: 最小值>=0,从0号出发可以直接到达
509+
// 情况3: min为负值,从后向前看,能把min填平的节点就是出发节点
510+
for (i <- gas.length - 1 to 0 by -1) {
511+
var rest = gas(i) - cost(i)
512+
min += rest
513+
if (min >= 0) return i
514+
}
515+
-1
516+
}
517+
}
518+
```
519+
520+
贪心算法,方法二:
521+
522+
```scala
523+
object Solution {
524+
def canCompleteCircuit(gas: Array[Int], cost: Array[Int]): Int = {
525+
var curSum = 0
526+
var totalSum = 0
527+
var start = 0
528+
for (i <- gas.indices) {
529+
curSum += (gas(i) - cost(i))
530+
totalSum += (gas(i) - cost(i))
531+
if (curSum < 0) {
532+
start = i + 1 // 起始位置更新
533+
curSum = 0 // curSum从0开始
534+
}
535+
}
536+
if (totalSum < 0) return -1 // 说明怎么走不可能跑一圈
537+
start
538+
}
539+
}
540+
```
541+
474542
-----------------------
475543
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /