mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
添加 0209.长度最小的子数组.md Scala版本
This commit is contained in:
@ -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>
|
||||
|
Reference in New Issue
Block a user