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

相关推荐
gCode Teacher 格码致知12 分钟前
Python基础教学:Python的openpyxl和python-docx模块结合Excel和Word模板进行数据写入-由Deepseek产生
python·excel
大胆飞猪1 小时前
递归、剪枝、回溯算法---全排列、子集问题(力扣.46,78)
算法·leetcode·剪枝
君不见,青丝成雪1 小时前
网关整合验签
大数据·数据结构·docker·微服务·系统架构
Destiny_where2 小时前
Agent平台-RAGFlow(2)-源码安装
python·ai
molunnnn3 小时前
第四章 Agent的几种经典范式
开发语言·python
Kisorge3 小时前
【电机控制】基于STM32F103C8T6的二轮平衡车设计——LQR线性二次线控制器(算法篇)
stm32·嵌入式硬件·算法
linuxxx1104 小时前
django测试缓存命令的解读
python·缓存·django
hnjzsyjyj4 小时前
洛谷 P12141:[蓝桥杯 2025 省 A] 红黑树
数据结构·蓝桥杯·二叉树
铭哥的编程日记4 小时前
深入浅出蓝桥杯:算法基础概念与实战应用(二)基础算法(下)
算法·职场和发展·蓝桥杯
Swift社区4 小时前
LeetCode 421 - 数组中两个数的最大异或值
算法·leetcode·职场和发展