有序数组的平方(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

相关推荐
Warson_L11 分钟前
Python 函数的艺术 (Functions)
python
Warson_L15 分钟前
Python 流程控制与逻辑
后端·python
long_songs18 分钟前
手柄键盘映射器【github链接见文末 】
python·游戏·计算机外设·pygame·软件推荐·手柄映射键盘
袋鼠云数栈19 分钟前
集团数字化统战实战:统一数据门户与全业态监管体系构建
大数据·数据结构·人工智能·多模态
必然秃头21 分钟前
Python 环境安装及项目构建指南
python
Warson_L24 分钟前
Python 四大组合数据类型 (Collection Types)
后端·python
廋到被风吹走24 分钟前
【AI】Codex 多语言实测:Python/Java/JS/SQL 效果横评
java·人工智能·python
Warson_L35 分钟前
Python 数据类型核心笔记
python
小月球~1 小时前
天梯赛 · 并查集
数据结构·算法
仍然.1 小时前
算法题目---模拟
java·javascript·算法