Merge pull request #1305 from ZongqinWang/patch01

添加(0977.有序数组的平方 和 0209.长度最小的子数组) Scala版本
This commit is contained in:
程序员Carl
2022-05-27 10:16:00 +08:00
committed by GitHub
2 changed files with 82 additions and 0 deletions

View File

@ -400,6 +400,54 @@ class Solution {
}
}
```
Scala:
滑动窗口:
```scala
object Solution {
def minSubArrayLen(target: Int, nums: Array[Int]): Int = {
var result = Int.MaxValue // 返回结果,默认最大值
var left = 0 // 慢指针当sum>=target向右移动
var sum = 0 // 窗口值的总和
for (right <- 0 until nums.length) {
sum += nums(right)
while (sum >= target) {
result = math.min(result, right - left + 1) // 产生新结果
sum -= nums(left) // 左指针移动,窗口总和减去左指针的值
left += 1 // 左指针向右移动
}
}
// 相当于三元运算符return关键字可以省略
if (result == Int.MaxValue) 0 else result
}
}
```
暴力解法:
```scala
object Solution {
def minSubArrayLen(target: Int, nums: Array[Int]): Int = {
import scala.util.control.Breaks
var res = Int.MaxValue
var subLength = 0
for (i <- 0 until nums.length) {
var sum = 0
Breaks.breakable(
for (j <- i until nums.length) {
sum += nums(j)
if (sum >= target) {
subLength = j - i + 1
res = math.min(subLength, res)
Breaks.break()
}
}
)
}
// 相当于三元运算符
if (res == Int.MaxValue) 0 else res
}
}
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

View File

@ -358,7 +358,41 @@ class Solution {
}
}
```
Scala:
双指针:
```scala
object Solution {
def sortedSquares(nums: Array[Int]): Array[Int] = {
val res: Array[Int] = new Array[Int](nums.length)
var top = nums.length - 1
var i = 0
var j = nums.length - 1
while (i <= j) {
if (nums(i) * nums(i) <= nums(j) * nums(j)) {
// 当左侧平方小于等于右侧res数组顶部放右侧的平方并且top下移j左移
res(top) = nums(j) * nums(j)
top -= 1
j -= 1
} else {
// 当左侧平方大于右侧res数组顶部放左侧的平方并且top下移i右移
res(top) = nums(i) * nums(i)
top -= 1
i += 1
}
}
res
}
}
```
骚操作(暴力思路):
```scala
object Solution {
def sortedSquares(nums: Array[Int]): Array[Int] = {
nums.map(x=>{x*x}).sortWith(_ < _)
}
}
```
-----------------------