Update 0977.有序数组的平方.md

This commit is contained in:
jianghongcheng
2023-05-03 15:19:23 -05:00
committed by GitHub
parent 53fbfc8339
commit 934dd4e313

View File

@ -140,22 +140,37 @@ class Solution {
Python Python
```Python ```Python
版本一双指针法
class Solution: class Solution:
def sortedSquares(self, nums: List[int]) -> List[int]: def sortedSquares(self, nums: List[int]) -> List[int]:
n = len(nums) l, r, i = 0, len(nums)-1, len(nums)-1
i,j,k = 0,n - 1,n - 1 res = [float('inf')] * len(nums) # 需要提前定义列表,存放结果
ans = [-1] * n while l <= r:
while i <= j: if nums[l] ** 2 < nums[r] ** 2: # 左右边界进行对比,找出最大值
lm = nums[i] ** 2 res[i] = nums[r] ** 2
rm = nums[j] ** 2 r -= 1 # 右指针往左移动
if lm > rm:
ans[k] = lm
i += 1
else: else:
ans[k] = rm res[i] = nums[l] ** 2
j -= 1 l += 1 # 左指针往右移动
k -= 1 i -= 1 # 存放结果的指针需要往前平移一位
return ans return res
```
```Python
版本二暴力排序法
class Solution:
def sortedSquares(self, nums: List[int]) -> List[int]:
for i in range(len(nums)):
nums[i] *= nums[i]
nums.sort()
return nums
```
```Python
版本三暴力排序法+列表推导法
class Solution:
def sortedSquares(self, nums: List[int]) -> List[int]:
return sorted(x*x for x in nums)
``` ```
Go Go