添加 0977.有序数组的平方.md Scala版本
This commit is contained in:
parent
cf4c25b891
commit
cc2c2adb09
|
|
@ -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(_ < _)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
-----------------------
|
-----------------------
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue