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

相关推荐
念何架构之路7 分钟前
Go语言加密算法
数据结构·算法·哈希算法
AI科技星9 分钟前
《数学公理体系·第三部·数术几何》(2026 年版)
c语言·开发语言·线性代数·算法·矩阵·量子计算·agi
失去的青春---夕阳下的奔跑15 分钟前
560. 和为 K 的子数组
数据结构·算法·leetcode
PILIPALAPENG37 分钟前
Python 语法速成指南:前端开发者视角(JS 类比版)
前端·人工智能·python
黎阳之光1 小时前
黎阳之光:以视频孪生重构智慧医院信息化,打造高标项目核心竞争力
大数据·人工智能·物联网·算法·数字孪生
丷丩1 小时前
三级缓存下MVT地图瓦片服务性能优化策略
算法·缓存·性能优化·gis·geoai-up
m0_629494731 小时前
LeetCode 热题 100-----25.回文链表
数据结构·算法·leetcode·链表
用户8356290780511 小时前
Python 操作 PowerPoint 页眉与页脚指南
后端·python
枫叶林FYL2 小时前
项目九:异步高性能爬虫与数据采集中枢 —— 基于 Crawl<sub>4</sub>AI 与 Playwright 的现代化数据采集平台 项目总览
爬虫·python·深度学习·wpf
猫猫的小茶馆2 小时前
【Python】函数与模块化编程
linux·开发语言·arm开发·驱动开发·python·stm32