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

相关推荐
样例过了就是过了11 小时前
LeetCode热题100 柱状图中最大的矩形
数据结构·c++·算法·leetcode
weixin_4193497911 小时前
Python 项目中生成 requirements.txt 文件
开发语言·python
wsoz11 小时前
Leetcode哈希-day1
算法·leetcode·哈希算法
阿Y加油吧11 小时前
LeetCode 二叉搜索树双神题通关!有序数组转平衡 BST + 验证 BST,小白递归一把梭
java·算法·leetcode
第一程序员12 小时前
Python与区块链:非科班转码者的指南
python·github
BlockChain88812 小时前
区块链的组件:从数据结构到去中心化共识
数据结构·去中心化·区块链
liu****12 小时前
LangChain-AI应用开发框架(六)
人工智能·python·langchain·大模型应用·本地部署大模型
witAI12 小时前
**AI仿真人剧制作2025推荐,专业团队与创新技术引领未来**
人工智能·python
liuyao_xianhui12 小时前
优选算法_最小基因变化_bfs_C++
java·开发语言·数据结构·c++·算法·哈希算法·宽度优先
♪-Interpretation12 小时前
第五节:Python的流程控制语句
python