【算法-数组】有序数组的平方

这里写自定义目录标题

一、题目

给你一个按 非递减顺序 排序的整数数组 nums,返回 每个数字的平方 组成的新数组,要求也按 非递减顺序 排序。

示例 1:

输入:nums = -4,-1,0,3,10

输出:0,1,9,16,100

解释:平方后,数组变为 16,1,0,9,100

排序后,数组变为 0,1,9,16,100

二、双指针解法

不停地比较首尾元素平方的大小,并将较大的放到一个新的结果数组中

空间复杂度 o(n) 时间复杂度o(n)

java 复制代码
public class SortArraySquare {

    public static int[] sortedSquares(int[] nums) {
        int[] res = new int[nums.length];
        int k = nums.length - 1;

        for (int i = 0, j = k; i <= j; ) {
            if (nums[i] * nums[i] > nums[j] * nums[j]) {
                res[k--] = nums[i] * nums[i];
                i++;
            } else {
                res[k--] = nums[j] * nums[j];
                j--;
            }
        }

        return res;
    }

    public static void main(String[] args) {

        int[] nums = {-4, -1, 0, 3, 10};
        int[] res = SortArraySquare.sortedSquares(nums);
        for (int i = 0; i < res.length; i++) {
            System.out.print(res[i] + " ");
        }
    }

}
相关推荐
祖力5529 分钟前
Linux应用软件编程:目录IO与framebuffer
linux·运维·算法·framebuffer·目录io
名字还没想好☜35 分钟前
Go 用 slices/maps 标准库泛型函数:告别手写 Contains、Sort、去重(Go 1.21)
开发语言·后端·算法·golang·go
地平线开发者36 分钟前
【模型轻量化专题】深度学习模型为什么需要轻量化
算法
_Narcissus_1 小时前
链表算法题和静态链表
数据结构·c++·笔记·算法·链表·ai·力扣
Lyyaoo.1 小时前
【普通数组】【中等】除了自身以外数组的乘积
数据结构·算法·leetcode
threerocks1 小时前
《The AI-Native SDLC Playbook》万字拆解
算法·aigc·ai编程
夏玉林的学习之路2 小时前
算法8.环形队列
算法
O。O蛋黄酥啊2 小时前
GraphRAG 和 LightRAG 详解与对比
人工智能·python·算法·rag·graphrag·lightrag
Σίσυφος19002 小时前
depth_from_focus 详解
算法
疯狂打码的少年3 小时前
【数据结构】八大排序算法对比总结(时间/空间/稳定性)
数据结构·笔记·算法