From 32018ff79afa8fb65cdf69445c9d93a34e648d54 Mon Sep 17 00:00:00 2001 From: ZongqinWang <1722249371@qq.com> Date: Mon, 13 Jun 2022 20:53:11 +0800 Subject: [PATCH 1/3] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200135.=E5=88=86?= =?UTF-8?q?=E5=8F=91=E7=B3=96=E6=9E=9C.md=20Scala=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0135.分发糖果.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/problems/0135.分发糖果.md b/problems/0135.分发糖果.md index 3456a04c..a805d0d4 100644 --- a/problems/0135.分发糖果.md +++ b/problems/0135.分发糖果.md @@ -324,6 +324,31 @@ function candy(ratings: number[]): number { }; ``` +### Scala + +```scala +object Solution { + def candy(ratings: Array[Int]): Int = { + var candyVec = new Array[Int](ratings.length) + for (i <- candyVec.indices) candyVec(i) = 1 + // 从前向后 + for (i <- 1 until candyVec.length) { + if (ratings(i) > ratings(i - 1)) { + candyVec(i) = candyVec(i - 1) + 1 + } + } + + // 从后向前 + for (i <- (candyVec.length - 2) to 0 by -1) { + if (ratings(i) > ratings(i + 1)) { + candyVec(i) = math.max(candyVec(i), candyVec(i + 1) + 1) + } + } + + candyVec.sum // 求和 + } +} +``` ----------------------- From 6867c9c5bfd379a2f6e8afb09026cb0e759bc8dc Mon Sep 17 00:00:00 2001 From: ZongqinWang <1722249371@qq.com> Date: Mon, 13 Jun 2022 21:21:22 +0800 Subject: [PATCH 2/3] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200860.=E6=9F=A0?= =?UTF-8?q?=E6=AA=AC=E6=B0=B4=E6=89=BE=E9=9B=B6.md=20Scala=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0860.柠檬水找零.md | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/problems/0860.柠檬水找零.md b/problems/0860.柠檬水找零.md index aa09e1c6..4a676b43 100644 --- a/problems/0860.柠檬水找零.md +++ b/problems/0860.柠檬水找零.md @@ -328,6 +328,37 @@ function lemonadeChange(bills: number[]): boolean { ``` +### Scala + +```scala +object Solution { + def lemonadeChange(bills: Array[Int]): Boolean = { + var fiveNum = 0 + var tenNum = 0 + + for (i <- bills) { + if (i == 5) fiveNum += 1 + if (i == 10) { + if (fiveNum <= 0) return false + tenNum += 1 + fiveNum -= 1 + } + if (i == 20) { + if (fiveNum > 0 && tenNum > 0) { + tenNum -= 1 + fiveNum -= 1 + } else if (fiveNum >= 3) { + fiveNum -= 3 + } else { + return false + } + } + } + true + } +} +``` + -----------------------