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

相关推荐
FriendshipT1 分钟前
Ultralytics:解读C3Ghost模块
人工智能·pytorch·python·深度学习·目标检测
Java面试题总结5 分钟前
Vue3流式调用大模型接口完整实践
后端·python
怪兽学LLM9 分钟前
AI Agent 记忆系统设计:长短期记忆如何实现?什么时候存?什么时候查?
人工智能·python
DFT计算杂谈12 分钟前
DeepSeek 集群服务器无root本地部署指南
数据库·人工智能·python·opencv·算法
卷无止境14 分钟前
Python 跨平台 GUI 解决方案全景报告
前端·python
qq_4542450317 分钟前
GraphFoundation — 通用图基础框架
算法·架构
不一样的故事1261 小时前
军工行业合规与基础认知
数据结构·经验分享·算法
圣保罗的大教堂6 小时前
leetcode 3867. 数对的最大公约数之和 中等
leetcode
To_OC9 小时前
LC 15 三数之和:双指针不难,难的是把去重做对
javascript·算法·leetcode
benchmark_cc10 小时前
如何用 Python + QuantDash 快速构建高胜率“配对交易(Pairs Trading)”策略?
开发语言·人工智能·python·pandas·量化交易·quantdash