977. Squaring an Ordered Array
977. Squaring an Ordered Array
topic
Given an array of integers nums sorted in non-decreasing order, return a new array consisting of the square of each number, also sorted in non-decreasing order.
Input: nums = [-4,-1,0,3,10]
Output: [0,1,9,16,100]
Explanation: After squaring, the array becomes [16,1,0,9,100]
After sorting, the array becomes is [0,1,9,16,100]
Input: nums = [-7,-3,2,3,11]
Output: [4,9,9,49,121]
the code
class Solution(object):
def sortedSquares(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
n=len(nums)
ans=[-1]*n #新建数组ans = [-1 for _ in range(n)]
l,r,i=0,n-1,n-1
while l<=r:
if nums[l]*nums[l]>nums[r]*nums[r]:
ans[i]=nums[l]*nums[l]
l+=1
else:
ans[i]=nums[r]*nums[r]
r-=1
i-=1
return ans
Summarize
- Review the double pointer, move to the left and right respectively
- ans=[-1]*n #New array ans = [-1 for _ in range(n)]