mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 08:50:15 +08:00
Update 0977.有序数组的平方.md
This commit is contained in:
@ -140,22 +140,37 @@ class Solution {
|
||||
|
||||
Python:
|
||||
```Python
|
||||
(版本一)双指针法
|
||||
class Solution:
|
||||
def sortedSquares(self, nums: List[int]) -> List[int]:
|
||||
n = len(nums)
|
||||
i,j,k = 0,n - 1,n - 1
|
||||
ans = [-1] * n
|
||||
while i <= j:
|
||||
lm = nums[i] ** 2
|
||||
rm = nums[j] ** 2
|
||||
if lm > rm:
|
||||
ans[k] = lm
|
||||
i += 1
|
||||
l, r, i = 0, len(nums)-1, len(nums)-1
|
||||
res = [float('inf')] * len(nums) # 需要提前定义列表,存放结果
|
||||
while l <= r:
|
||||
if nums[l] ** 2 < nums[r] ** 2: # 左右边界进行对比,找出最大值
|
||||
res[i] = nums[r] ** 2
|
||||
r -= 1 # 右指针往左移动
|
||||
else:
|
||||
ans[k] = rm
|
||||
j -= 1
|
||||
k -= 1
|
||||
return ans
|
||||
res[i] = nums[l] ** 2
|
||||
l += 1 # 左指针往右移动
|
||||
i -= 1 # 存放结果的指针需要往前平移一位
|
||||
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:
|
||||
|
Reference in New Issue
Block a user