先求平方再排序——时间:O(nlgn)
双指针法——时间:O(n)
先贴我的代码
class Solution(object):def sortedSquares(self, A):""":type A: List[int]:rtype: List[int]"""left = -1 if A[0]>=0 else len(A)-1right = len(A) if A[-1]<0 else 0ans = []for i in range(len(A)-1):if A[i] < 0 and A[i+1] >= 0:left = iright = i+1breakwhile left>=0 and right<len(A):if -A[left] <= A[right]:ans.append(A[left]*A[left])left -= 1else:ans.append(A[right]*A[right])right += 1if left>=0:for i in range(left, -1, -1):ans.append(A[i]*A[i])elif right<len(A):for i in range(right, len(A)):ans.append(A[i]*A[i])return ans
力扣官网介绍另一种双指针法,逆向思维:
从两端比较,选取大的,逆序放入数组中
class Solution(object):def sortedSquares(self, A):""":type A: List[int]:rtype: List[int]"""ans = [0]*len(A)left = 0now = right = len(A)-1while right>=left:if A[left]*A[left] > A[right]*A[right]:ans[now] = A[left]*A[left]left += 1else:ans[now] = A[right]*A[right]right -= 1now -= 1return ans