4. leetcode 数组平方和的排序

1. 问题
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.
示例一:

Input: [-4,-1,0,3,10]
Output: [0,1,9,16,100]

示例二:

Input: [-7,-3,2,3,11]
Output: [4,9,9,49,121]

注重:

1 <= A.length <= 10000
-10000 <= A[i] <= 10000
A is sorted in non-decreasing order.

2. 本身的解法:
Javascript

var sortedSquares = function(A) {
    return A.map(i => i *i).sort((a, b) => a - b)
};

Runtime: 172 ms, faster than 53.38% of Python3 online submissions for

Squares of a Sorted Array. Memory Usage: 15.3 MB, less than 5.22% of

Python3 online submissions for Squares of a Sorted Array.

3. 其他解法

Python

def sortedSquares(self, A):
    answer = [0] * len(A)
    l, r = 0, len(A) - 1
    while l <= r:
        left, right = abs(A[l]), abs(A[r])
        if left > right:
            answer[r - l] = left * left
            l += 1
        else:
            answer[r - l] = right * right
            r -= 1
    return answer
    原文作者:lllluull
    原文地址: https://segmentfault.com/a/1190000018672044
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞