leetcode

给定一个按非递减顺序排序的整数数组 A,返回每个数字的平方组成的新数组,要求也按非递减顺序排序。

例如
输入:[-4,-1,0,3,10]
输出:[0,1,9,16,100]
例如
输入:[-7,-3,2,3,11]
输出:[4,9,9,49,121]

提示:

  • 1 <= A.length <= 10000
  • -10000 <= A[i] <= 10000
  • A 已按非递减顺序排序。

思考

按照题意操作就可以了。

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

结果:

执行用时 : 240 ms, 在Squares of a Sorted Array的Python提交中击败了97.70% 的用户
内存消耗 : 13.8 MB, 在Squares of a Sorted Array的Python提交中击败了20.62% 的用户

提交时间 状态 执行用时 内存消耗 语言
几秒前 通过 240 ms 13.8MB python

## 简化

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

结果:

执行用时 : 244 ms, 在Squares of a Sorted Array的Python提交中击败了95.74% 的用户
内存消耗 : 13.7 MB, 在Squares of a Sorted Array的Python提交中击败了27.20% 的用户

提交时间 状态 执行用时 内存消耗 语言
几秒前 通过 244 ms 13.7MB python