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

相关推荐
戴西软件1 分钟前
国内有哪些数据轻量化格式转换软件?
数据库·算法·安全·信息可视化·自动化·rpa
2401_844582954 分钟前
冷门技巧:AI模型可靠性测试的实用技巧:数
python
you鬰10 分钟前
datawhale--llm-algo-leetcode5️⃣
python·datawhale
老洋葱Mr_Onion23 分钟前
【C++】CSP-J初赛模拟卷七错题整理(作者自用)
c++·算法·深度优先
λqaq730 分钟前
MySQL 数据库基础(2)约束、用户权限、远程连接、外键与 TCP/UDP 理解
linux·数据库·python·tcp/ip·mysql
人工干智能33 分钟前
科普:pandas 时间偏移别名:ts.resample(“5Min“).sum()
python·pandas
Nil20836 分钟前
leetcode 114二叉树展开为链表
leetcode·链表·深度优先
开源量化GO43 分钟前
最新AI辅助量化表达:先理清规则,再按需求选工具
人工智能·python
土星云SaturnCloud1 小时前
Real-ESRGAN超分辨率算法原理与边缘侧部署实践
服务器·算法·ai·边缘计算·real-esrgan
cz07101 小时前
hot100_搜索二维矩阵 II
算法·leetcode