题目
'''
Description: 977.有序数组的平方
Autor: 365JHWZGo
Date: 2022-02-09 17:02:27
LastEditors: 365JHWZGo
LastEditTime: 2022-02-09 17:11:25
'''
难度
easy
思路
先进行排序,在进行平方
代码
class Solution(object):
def sortedSquares(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
nums.sort(key=lambda x:abs(x))
return [n**2 for n in nums]
class Solution(object):
def sortedSquares(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
a = [n**2 for n in nums]
a.sort(key=lambda x:abs(x))
return a
class Solution(object):
def sortedSquares(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
res = [-1]*len(nums)
l,r,index = 0,len(nums)-1,len(nums)-1
while l<=r:
if abs(nums[l])<=abs(nums[r]):
res[index] = nums[r]**2
r-=1
index-=1
else:
res[index] = nums[l]**2
l+=1
index-=1
return res