添加 0977.有序数组的平方.md Scala版本

This commit is contained in:
ZongqinWang
2022-05-11 16:03:22 +08:00
parent cf4c25b891
commit cc2c2adb09

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(_ < _)
}
}
```
-----------------------