有序数组的平方(LeetCode)

题目

给你一个按 非递减顺序 排序的整数数组 nums,返回 每个数字的平方 组成的新数组,要求也按 非递减顺序 排序。

解题

以下算法时间复杂度为

python 复制代码
def sortedSquares(nums):
    n = len(nums)
    result = [0] * n  # 创建一个结果数组,长度与 nums 相同
    left, right = 0, n - 1  # 初始化左右指针
    position = n - 1  # 初始化结果数组的插入位置

    while left <= right:
        left_square = nums[left] ** 2
        right_square = nums[right] ** 2
        if left_square > right_square:
            result[position] = left_square
            left += 1
        else:
            result[position] = right_square
            right -= 1
        position -= 1

    return result


nums = [-4, -1, 0, 3, 10]
print(sortedSquares(nums))  # 输出: [0, 1, 9, 16, 100]

nums = [-7, -3, 2, 3, 11]
print(sortedSquares(nums))  # 输出: [4, 9, 9, 49, 121]

0, 1, 9, 16, 100

4, 9, 9, 49, 121

相关推荐
西猫雷婶7 小时前
pytorch基本运算-分离计算
人工智能·pytorch·python·深度学习·神经网络·机器学习
pzx_0017 小时前
【LeetCode】14. 最长公共前缀
算法·leetcode·职场和发展
数新网络7 小时前
PyTorch
人工智能·pytorch·python
self_myth7 小时前
算法与数据结构实战技巧:从复杂度分析到数学优化
算法
自信的小螺丝钉7 小时前
【大模型手撕】pytorch实现LayerNorm, RMSNorm
人工智能·pytorch·python·归一化·rmsnorm·layernorm
深耕AI7 小时前
PyTorch图像预处理:ToTensor()与Normalize()的本质区别
人工智能·pytorch·python
songx_998 小时前
leetcode10(跳跃游戏 II)
数据结构·算法·leetcode
鲸屿1958 小时前
python之socket网络编程
开发语言·网络·python
里昆8 小时前
【AI】Tensorflow在jupyterlab中运行要注意的问题
人工智能·python·tensorflow
AI视觉网奇8 小时前
pycharm 最新版上一次编辑位置
python