leetcode 977. Squares of a Sorted Array( Python )

902 阅读20分钟

描述

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.

解析

对列表中的元素求平方然后排序即可,需要特别注意的是求平方之后是否会超出int的最大值。还好题目给了A[i]的范围只有 ±10000,那么平方是1个亿,不会超过int最大,所以是安全的。时间复杂度为O(NlogN)。

解答

class Solution(object):
def sortedSquares(self, A):
    """
    :type A: List[int]
    :rtype: List[int]
    """
    A = [x*x for x in A]
    A.sort()
    return A

运行结果

Runtime: 212 ms, faster than 40.42% of Python online submissions for Squares of a Sorted Array.
Memory Usage: 14 MB, less than 7.65% of Python online submissions for Squares of a Sorted Array.

每日格言:与魔鬼战斗的人,应当小心自己不要成为魔鬼。当你远远凝视深渊时,深渊也在凝视你。

感谢支持 支付宝

支付宝

微信

微信