有序数组的平方-数组977-python

没看答案,负数的平方也是整数,所以先把输入数组中的所有负数变成正数,然后把所有元素的平方加入到新数组中并排序输出。

class Solution:
    def sortedSquares(self, nums: List[int]) -> List[int]:
        res = []
        
        for i in nums:
            if i < 0:
                i = -i
            res.append(i**2)
        
        res = sorted(res)

        return res

双指针:使用两个指针分别指向位置 0 和 n-1,每次比较两个指针对应的数,选择较大的那个逆序放入答案并移动指针。

class Solution:
    def sortedSquares(self, nums: List[int]) -> List[int]:
        res = [0] * len(nums)
        i, j, pos = 0, len(nums)-1, len(nums)-1


        while i != j:
            if nums[i]**2 <= nums[j]**2:
                res[pos] = nums[j]**2
                j -= 1
            else:
                res[pos] = nums[i]**2
                i += 1 
            
            pos -= 1
        
        res[0] = nums[i]**2
        
        return res
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值