diff --git a/problems/0134.加油站.md b/problems/0134.加油站.md index e6dec44b..e5d50a9b 100644 --- a/problems/0134.加油站.md +++ b/problems/0134.加油站.md @@ -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 + } +} +``` + -----------------------