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

相关推荐
Zephyrtoria1 小时前
区间合并:区间合并问题
java·开发语言·数据结构·算法
柏箱3 小时前
容器里有10升油,现在只有两个分别能装3升和7升油的瓶子,需要将10 升油等分成2 个5 升油。程序输出分油次数最少的详细操作过程。
算法·bfs
2501_915374353 小时前
LangChain自动化工作流实战教程:从任务编排到智能决策
python·langchain·自动化
chilavert3184 小时前
深入剖析AI大模型:Prompt 开发工具与Python API 调用与技术融合
人工智能·python·prompt
Hello eveybody4 小时前
C++介绍整数二分与实数二分
开发语言·数据结构·c++·算法
Mallow Flowers6 小时前
Python训练营-Day31-文件的拆分和使用
开发语言·人工智能·python·算法·机器学习
梦境虽美,却不长6 小时前
数据结构 学习 队列 2025年6月14日 11点22分
数据结构·学习·队列
蓝婷儿6 小时前
Python 爬虫入门 Day 2 - HTML解析入门(使用 BeautifulSoup)
爬虫·python·html
GalaxyPokemon7 小时前
LeetCode - 704. 二分查找
数据结构·算法·leetcode
leo__5207 小时前
matlab实现非线性Granger因果检验
人工智能·算法·matlab