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

相关推荐
张彦峰ZYF1 小时前
高频面试题(含笔试高频算法整理)基本总结回顾63
linux·运维·算法
过期动态2 小时前
【动手学深度学习】卷积神经网络(CNN)入门
人工智能·python·深度学习·pycharm·cnn·numpy
无敌的牛2 小时前
vector模拟实现(2)
数据结构
alphaTao2 小时前
LeetCode 每日一题 2025/3/31-2025/4/6
算法·leetcode
Andrew_Ryan2 小时前
android use adb instsll cacerts
算法·架构
Wx120不知道取啥名3 小时前
C语言跳表(Skip List)算法:数据世界的“时光穿梭机”
c语言·数据结构·算法·list·跳表算法
禾小西4 小时前
Java 逐梦力扣之旅_[204. 计数质数]
java·算法·leetcode
LuckyLay4 小时前
LeetCode算法题(Go语言实现)_32
算法·leetcode·golang
ゞ 正在缓冲99%…4 小时前
leetcode295.数据流的中位数
java·数据结构·算法·leetcode·