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

相关推荐
2401_874732533 小时前
为你的Python脚本添加图形界面(GUI)
jvm·数据库·python
Fly Wine4 小时前
Leetcode之有效字母异位词
算法·leetcode·职场和发展
FreakStudio4 小时前
0 元学嵌入式 GUI!保姆级 LVGL+MicroPython 教程开更,从理论到实战全搞定
python·单片机·嵌入式·面向对象·电子diy
程序员夏末5 小时前
【LeetCode | 第七篇】算法笔记
笔记·算法·leetcode
剑穗挂着新流苏3126 小时前
117_PyTorch 实战:利用训练好的模型进行单张图片验证
人工智能·python·深度学习
csdn_aspnet6 小时前
C/C++ 两个凸多边形之间的切线(Tangents between two Convex Polygons)
c语言·c++·算法
数据皮皮侠6 小时前
中国城市间地理距离矩阵(2024)
大数据·数据库·人工智能·算法·制造
Lethehong6 小时前
Python Selenium全栈指南:从自动化入门到企业级实战
python·selenium·测试工具·自动化
3GPP仿真实验室6 小时前
深度解析基站接收机核心算法:从 MRC 到 IRC 的空间滤波演进
算法
Boop_wu6 小时前
[Java 算法] 动态规划(1)
算法·动态规划