977. Squares of a Sorted Array
Python
Cacluate and Sort
class Solution:
def sortedSquares(self, nums: List[int]) -> List[int]:
return sorted([i**2 for i in nums])
Two Pointer
- Use the adventage from the
sorted
natural
class Solution:
def sortedSquares(self, nums: List[int]) -> List[int]:
length = len(nums)
result = [0] * length
left, right = 0, length-1
for i in range(length-1, -1, -1):
if abs(nums[left]) < abs(nums[right]):
result[i] = nums[right] ** 2
right -= 1
else:
result[i] = nums[left] ** 2
left += 1
return result