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

相关推荐
CoderYanger1 分钟前
递归、搜索与回溯-记忆化搜索:38.最长递增子序列
java·算法·leetcode·1024程序员节
Trouville011 小时前
Pycharm软件初始化设置,字体和shell路径如何设置到最舒服
ide·python·pycharm
高-老师1 小时前
WRF模式与Python融合技术在多领域中的应用及精美绘图
人工智能·python·wrf模式
小白学大数据1 小时前
基于Splash的搜狗图片动态页面渲染爬取实战指南
开发语言·爬虫·python
xlq223221 小时前
22.多态(下)
开发语言·c++·算法
零日失眠者1 小时前
【文件管理系列】003:重复文件查找工具
后端·python
CoderYanger1 小时前
C.滑动窗口-越短越合法/求最长/最大——2958. 最多 K 个重复元素的最长子数组
java·数据结构·算法·leetcode·哈希算法·1024程序员节
FreeCode2 小时前
一文了解LangGraph智能体设计开发过程:Thinking in LangGraph
python·langchain·agent
西柚小萌新2 小时前
【深入浅出PyTorch】--9.使用ONNX进行部署并推理
人工智能·pytorch·python
nvd112 小时前
SSE 流式输出与 Markdown 渲染实现详解
javascript·python