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 + } +} +``` + -----------------------
diff --git a/problems/1005.K次取反后最大化的数组和.md b/problems/1005.K次取反后最大化的数组和.md index 8e161594..8d721b9f 100644 --- a/problems/1005.K次取反后最大化的数组和.md +++ b/problems/1005.K次取反后最大化的数组和.md @@ -289,6 +289,28 @@ function largestSumAfterKNegations(nums: number[], k: number): number { }; ``` +### Scala + +```scala +object Solution { + def largestSumAfterKNegations(nums: Array[Int], k: Int): Int = { + var num = nums.sortWith(math.abs(_) > math.abs(_)) + + var kk = k // 因为k是不可变量,所以要赋值给一个可变量 + for (i <- num.indices) { + if (num(i) < 0 && kk > 0) { + num(i) *= -1 // 取反 + kk -= 1 + } + } + + // kk对2取余,结果为0则为偶数不需要取反,结果为1为奇数,只需要对最后的数字进行反转就可以 + if (kk % 2 == 1) num(num.size - 1) *= -1 + + num.sum // 最后返回数字的和 + } +} +```