题目链接:https://leetcode-cn.com/problems/squares-of-a-sorted-array/
难度:简单
描述:
给你一个按 非递减顺序 排序的整数数组 nums
,返回 每个数字的平方 组成的新数组,要求也按 非递减顺序 排序。
提示:
数组大小:[1, 10000]
题解
- 直接求平方再排序
双指针
class Solution:
def sortedSquares(self, nums: List[int]) -> List[int]:
length = len(nums)
ret = [0] * length
left, right = 0, length - 1
while left <= right:
if nums[left] * nums[left] <= nums[right] * nums[right]:
ret[length-1] = nums[right] * nums[right]
right -= 1
else:
ret[length-1] = nums[left] * nums[left]
left += 1
length -= 1
return ret