添加 0134.加油站.md Scala版本

This commit is contained in:
ZongqinWang
2022-06-12 13:46:58 +08:00
parent 882c19c3e2
commit 1da68a332c

View File

@ -471,5 +471,73 @@ int canCompleteCircuit(int* gas, int gasSize, int* cost, int costSize){
}
```
### Scala
暴力解法:
```scala
object Solution {
def canCompleteCircuit(gas: Array[Int], cost: Array[Int]): Int = {
for (i <- cost.indices) {
var rest = gas(i) - cost(i)
var index = (i + 1) % cost.length // index为i的下一个节点
while (rest > 0 && i != index) {
rest += (gas(index) - cost(index))
index = (index + 1) % cost.length
}
if (rest >= 0 && index == i) return i
}
-1
}
}
```
贪心算法,方法一:
```scala
object Solution {
def canCompleteCircuit(gas: Array[Int], cost: Array[Int]): Int = {
var curSum = 0
var min = Int.MaxValue
for (i <- gas.indices) {
var rest = gas(i) - cost(i)
curSum += rest
min = math.min(min, curSum)
}
if (curSum < 0) return -1 // 情况1: gas的总和小于cost的总和不可能到达终点
if (min >= 0) return 0 // 情况2: 最小值>=0从0号出发可以直接到达
// 情况3: min为负值从后向前看能把min填平的节点就是出发节点
for (i <- gas.length - 1 to 0 by -1) {
var rest = gas(i) - cost(i)
min += rest
if (min >= 0) return i
}
-1
}
}
```
贪心算法,方法二:
```scala
object Solution {
def canCompleteCircuit(gas: Array[Int], cost: Array[Int]): Int = {
var curSum = 0
var totalSum = 0
var start = 0
for (i <- gas.indices) {
curSum += (gas(i) - cost(i))
totalSum += (gas(i) - cost(i))
if (curSum < 0) {
start = i + 1 // 起始位置更新
curSum = 0 // curSum从0开始
}
}
if (totalSum < 0) return -1 // 说明怎么走不可能跑一圈
start
}
}
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>