Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 871d96a

Browse files
committed
添加 0209.长度最小的子数组.md Scala版本
1 parent cc2c2ad commit 871d96a

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

‎problems/0209.长度最小的子数组.md‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -400,6 +400,54 @@ class Solution {
400400
}
401401
}
402402
```
403+
Scala:
404+
405+
滑动窗口:
406+
```scala
407+
object Solution {
408+
def minSubArrayLen(target: Int, nums: Array[Int]): Int = {
409+
var result = Int.MaxValue // 返回结果,默认最大值
410+
var left = 0 // 慢指针,当sum>=target,向右移动
411+
var sum = 0 // 窗口值的总和
412+
for (right <- 0 until nums.length) {
413+
sum += nums(right)
414+
while (sum >= target) {
415+
result = math.min(result, right - left + 1) // 产生新结果
416+
sum -= nums(left) // 左指针移动,窗口总和减去左指针的值
417+
left += 1 // 左指针向右移动
418+
}
419+
}
420+
// 相当于三元运算符,return关键字可以省略
421+
if (result == Int.MaxValue) 0 else result
422+
}
423+
}
424+
```
425+
426+
暴力解法:
427+
```scala
428+
object Solution {
429+
def minSubArrayLen(target: Int, nums: Array[Int]): Int = {
430+
import scala.util.control.Breaks
431+
var res = Int.MaxValue
432+
var subLength = 0
433+
for (i <- 0 until nums.length) {
434+
var sum = 0
435+
Breaks.breakable(
436+
for (j <- i until nums.length) {
437+
sum += nums(j)
438+
if (sum >= target) {
439+
subLength = j - i + 1
440+
res = math.min(subLength, res)
441+
Breaks.break()
442+
}
443+
}
444+
)
445+
}
446+
// 相当于三元运算符
447+
if (res == Int.MaxValue) 0 else res
448+
}
449+
}
450+
```
403451

404452
-----------------------
405453
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /