一道有意思的简单题:有序数组平方

    题目就大概知道要做什么了,我一开始想的比较简单:

    1. class Solution:
    2. def sortedSquares(self, nums: List[int]) -> List[int]:
    3. res = []
    4. left, right = 0, len(nums)-1
    5. while right > left:
    6. if abs(nums[left]) > abs(nums[right]):
    7. res.insert(0, nums[left]**2)
    8. left += 1
    9. else:
    10. res.insert(0, nums[right]**2)
    11. right -= 1
    12. res.insert(0, nums[left]**2)
    13. return res

    但是由于 python 的列表实现问题,insert 的执行速度比较慢,所以 leetcode 结果用了 200+ 时间
    比 99+% 的用户提交慢,太尴尬了

    之后想了一下,试试先尾插再反转:

    1. class Solution:
    2. def sortedSquares(self, nums: List[int]) -> List[int]:
    3. res = []
    4. left, right = 0, len(nums)-1
    5. while right > left:
    6. if abs(nums[left]) > abs(nums[right]):
    7. res.append(nums[left]**2)
    8. left += 1
    9. else:
    10. res.append(nums[right]**2)
    11. right -= 1
    12. res.append(nums[left]**2)
    13. res.reverse()
    14. return res

    结果快了不少,90+ 的时间
    然后看了题解,也是用时最短的解法:

    1. class Solution:
    2. def sortedSquares(self, nums: List[int]) -> List[int]:
    3. return sorted(num * num for num in nums)

    感觉自己好傻

    Life is short, You need Python