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

相关推荐
码农派大星。5 分钟前
Selenium在Pyhton应用
python·selenium·测试工具
崎岖Qiu24 分钟前
leetcode1343:大小为K的子数组(定长滑动窗口)
java·算法·leetcode·力扣·滑动窗口
day>day>up37 分钟前
django uwsgi启动报错failed to get the Python codec of the filesystem encoding
后端·python·django
Shun_Tianyou1 小时前
Python Day25 进程与网络编程
开发语言·网络·数据结构·python·算法
Giser探索家2 小时前
什么是2米分辨率卫星影像数据?
大数据·人工智能·数码相机·算法·分类·云计算
都叫我大帅哥2 小时前
LangGraph条件判断:让AI工作流"聪明"起来
python·langchain
编程研究坊3 小时前
Neo4j APOC插件安装教程
数据库·人工智能·python·neo4j
咩?3 小时前
SEABORN库函数(第十八节课内容总结)
开发语言·python·matplotlib·seaborn
万粉变现经纪人3 小时前
如何解决pip安装报错ModuleNotFoundError: No module named ‘transformers’问题
人工智能·python·beautifulsoup·pandas·scikit-learn·pip·ipython
jz_ddk3 小时前
[科普] AI加速器架构全景图:从GPU到光计算的算力革命
人工智能·学习·算法·架构