977. Squares of a Sorted Array

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.

nlog做法,全部先求平方数,然后排序

on做法用两个指针,一个指向开头一个指向结尾,然后谁的平方数大就放到答案数组的后面,移动对应的指针

class Solution(object):
    def sortedSquares(self, A):
        """
        :type A: List[int]
        :rtype: List[int]
        """
        l = 0
        r = len(A) - 1
        ans = [0] * len(A)
        index = len(A) - 1
        while l <= r:
            if A[l] * A[l] >= A[r] * A[r]:
                ans[index] = A[l] * A[l]
                index -= 1
                l += 1
            else:
                ans[index] = A[r] * A[r]
                index -= 1
                r -= 1
        return ans
原文地址:https://www.cnblogs.com/whatyouthink/p/13207553.html