lc977. 有序数组的平方

2022/4/29 23:17:03

本文主要是介绍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     

 



这篇关于lc977. 有序数组的平方的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程