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

相关推荐
地平线开发者1 小时前
【模型轻量化专题】衡量模型轻量性的指标
算法
用户7783366132112 小时前
用 React Hook 封装搜索数据:useSerp 的防抖、缓存与错误处理
python·api
学习星球4 小时前
OFDM技术精讲:正交性推导、循环前缀原理与80行Python链路仿真(附实测数据)
算法·面试·前端框架
65岁退休Coder6 小时前
LangGraph v1.2.9 节点容错策略 & 流式输出 & 持久化记忆管理
后端·python·langchain
ikun_文8 小时前
Django框架路由Router的使用
python·pycharm·django
IvanCodes8 小时前
Python 基础语法(二):字符串与常用操作
python
昭昭日月明8 小时前
LangChain 生态:从链到代理,开发者需要掌握的三大核心
python·langchain·agent
Csvn8 小时前
🐍 Day 8:面向对象编程
后端·python
程序员天天困9 小时前
向量检索不准怎么办:混合检索与 Rerank 重排序召回优化实战
后端·python·ai编程
alphaTao10 小时前
LeetCode 每日一题 2026/8/24-2026/8/30
python·算法·leetcode