mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 08:50:15 +08:00
@ -224,6 +224,36 @@ const sortedSquares = function (nums) {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Swift:
|
||||||
|
|
||||||
|
```swift
|
||||||
|
func sortedSquares(_ nums: [Int]) -> [Int] {
|
||||||
|
// 指向新数组最后一个元素
|
||||||
|
var k = nums.count - 1
|
||||||
|
// 指向原数组第一个元素
|
||||||
|
var i = 0
|
||||||
|
// 指向原数组最后一个元素
|
||||||
|
var j = nums.count - 1
|
||||||
|
// 初始化新数组(用-1填充)
|
||||||
|
var result = Array<Int>(repeating: -1, count: nums.count)
|
||||||
|
|
||||||
|
for _ in 0..<nums.count {
|
||||||
|
if nums[i] * nums[i] < nums[j] * nums[j] {
|
||||||
|
result[k] = nums[j] * nums[j]
|
||||||
|
j -= 1
|
||||||
|
} else {
|
||||||
|
result[k] = nums[i] * nums[i]
|
||||||
|
i += 1
|
||||||
|
}
|
||||||
|
k -= 1
|
||||||
|
}
|
||||||
|
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
-----------------------
|
-----------------------
|
||||||
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
||||||
* B站视频:[代码随想录](https://space.bilibili.com/525438321)
|
* B站视频:[代码随想录](https://space.bilibili.com/525438321)
|
||||||
|
Reference in New Issue
Block a user