mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
Merge pull request #1474 from wzqwtt/greedy05
添加(0135.分发糖果、0860.柠檬水找零、0406.根据身高重建队列) Scala版本
This commit is contained in:
@ -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 // 求和
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
-----------------------
|
||||
|
@ -354,8 +354,27 @@ function reconstructQueue(people: number[][]): number[][] {
|
||||
};
|
||||
```
|
||||
|
||||
### Scala
|
||||
|
||||
```scala
|
||||
object Solution {
|
||||
import scala.collection.mutable
|
||||
def reconstructQueue(people: Array[Array[Int]]): Array[Array[Int]] = {
|
||||
val person = people.sortWith((a, b) => {
|
||||
if (a(0) == b(0)) a(1) < b(1)
|
||||
else a(0) > b(0)
|
||||
})
|
||||
|
||||
var que = mutable.ArrayBuffer[Array[Int]]()
|
||||
|
||||
for (per <- person) {
|
||||
que.insert(per(1), per)
|
||||
}
|
||||
|
||||
que.toArray
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
-----------------------
|
||||
|
@ -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
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
-----------------------
|
||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||
|
Reference in New Issue
Block a user