- Squares of a Sorted Array Easy
1153
87
Add to List
Share Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order.
Example 1:
Input: [-4,-1,0,3,10] Output: [0,1,9,16,100] Example 2:
Input: [-7,-3,2,3,11] Output: [4,9,9,49,121]
Note:
1 <= A.length <= 10000 -10000 <= A[i] <= 10000 A is sorted in non-decreasing order.
思路:找到列表中非负值下标p,q=p-1,然后双指针插入新的列表
代码:python3
class Solution:
def sortedSquares(self, A: List[int]) -> List[int]:
p=0
q=p-1
for i in range(len(A)):
if A[i]>=0:
p=i
q=i-1
break
result=[]
while p<len(A) and q>=0:
p2=A[p]*A[p]
q2=A[q]*A[q]
if p2>q2:
result.append(q2)
q=q-1
else:
result.append(p2)
p=p+1
if p<len(A):
while p<len(A):
result.append(A[p]*A[p])
p=p+1
if q>=0:
while q>=0:
result.append(A[q]*A[q])
q=q-1
return result
if __name__ == '__main__':
print(Solution().sortedSquares([-7,-3,2,3,11]))
时间复杂度: O(2m) 空间复杂度:O(m)