mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 07:35:35 +08:00
Merge pull request #1459 from wzqwtt/greedy01
添加(0455.分发饼干、0376.摆动序列) Scala版本
This commit is contained in:
@ -375,7 +375,31 @@ function wiggleMaxLength(nums: number[]): number {
|
||||
};
|
||||
```
|
||||
|
||||
### Scala
|
||||
|
||||
```scala
|
||||
object Solution {
|
||||
def wiggleMaxLength(nums: Array[Int]): Int = {
|
||||
if (nums.length <= 1) return nums.length
|
||||
var result = 1
|
||||
var curDiff = 0 // 当前一对的差值
|
||||
var preDiff = 0 // 前一对的差值
|
||||
|
||||
for (i <- 1 until nums.length) {
|
||||
curDiff = nums(i) - nums(i - 1) // 计算当前这一对的差值
|
||||
// 当 curDiff > 0 的情况,preDiff <= 0
|
||||
// 当 curDiff < 0 的情况,preDiff >= 0
|
||||
// 这两种情况算是两个峰值
|
||||
if ((curDiff > 0 && preDiff <= 0) || (curDiff < 0 && preDiff >= 0)) {
|
||||
result += 1 // 结果集加 1
|
||||
preDiff = curDiff // 当前差值赋值给上一轮
|
||||
}
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
-----------------------
|
||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||
|
@ -296,5 +296,26 @@ int findContentChildren(int* g, int gSize, int* s, int sSize){
|
||||
}
|
||||
```
|
||||
|
||||
### Scala
|
||||
|
||||
```scala
|
||||
object Solution {
|
||||
def findContentChildren(g: Array[Int], s: Array[Int]): Int = {
|
||||
var result = 0
|
||||
var children = g.sorted
|
||||
var cookie = s.sorted
|
||||
// 遍历饼干
|
||||
var j = 0
|
||||
for (i <- cookie.indices) {
|
||||
if (j < children.size && cookie(i) >= children(j)) {
|
||||
j += 1
|
||||
result += 1
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
-----------------------
|
||||
<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