其他分享
首页 > 其他分享> > lc977. 有序数组的平方

lc977. 有序数组的平方

作者:互联网

class Solution:
    def sortedSquares(self, nums: List[int]) -> List[int]:
        if len(nums) == 0:
            return []
        if len(nums) == 1:
            return [nums[0] ** 2]
        result = []
        i = 0
        square_less_zero = []
        while i < len(nums) and nums[i] < 0:
            square_less_zero.append(nums[i] ** 2)
            i += 1
        j = len(square_less_zero) - 1
        while i < len(nums) and j >= 0:
            if nums[i] ** 2 <= square_less_zero[j]:
                result.append(nums[i] ** 2)
                i += 1
            else:
                result.append(square_less_zero[j])
                j -= 1
        if i < len(nums):
            while i < len(nums):
                result.append(nums[i] ** 2)
                i += 1
        if j >= 0: 
            while j >= 0:
                result.append(square_less_zero[j])
                j -= 1
        return result     

 

标签:平方,square,return,nums,less,lc977,len,zero,数组
来源: https://www.cnblogs.com/bidesen/p/16208562.html