有序数组的平方 的 逻辑

题目:

python代码:

双指针,从后往前排新数组:

class Solution:
    def sortedSquares(self, nums):
        n = len(nums)
        left = 0
        right = n-1
        result = [0] * n
        index = n - 1
        
        while left <= right:
            if nums[left] ** 2 > nums[right] ** 2 :
                result[index] = nums[left] ** 2
                left += 1
                index -= 1
            else:
                result[index] = nums[right] ** 2
                right -= 1
                index -= 1
        return result

双指针,从前往后排新数组再倒转:

class Solution:
    # def sortedSquares(self, nums: List[int]) -> List[int]:
    def sortedSquares(self, nums):
        n = len(nums)
        result = []
        left, right = 0, n - 1
        
        while left <= right:
            if nums[left] ** 2 > nums[right] ** 2:
                result.append(nums[left] ** 2)
                left += 1
            else:
                result.append(nums[right] ** 2)
                right -= 1
        
        return result[::-1]

DEBUG:

1、要求新数组是“非递减”,那么只需要考虑递减(也就是>)的这种情况,其他放到else里

2、我用的是先递增排序,然后再倒转的方法

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值