leetcode做题日记——977.有序数组的平方

本文介绍了如何在O(n)时间复杂度下,使用暴力求解和双指针法分别计算并按非递减顺序排列给定整数数组的每个元素平方。两种方法都涉及遍历数组并进行比较交换操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

示例 1:

输入:nums = [-4,-1,0,3,10]
输出:[0,1,9,16,100]
解释:平方后,数组变为 [16,1,0,9,100]
排序后,数组变为 [0,1,9,16,100]

示例 2:

输入:nums = [-7,-3,2,3,11]
输出:[4,9,9,49,121]

提示:

  • 1 <= nums.length <= 104
  • -104 <= nums[i] <= 104
  • nums 已按 非递减顺序 排序

进阶:

  • 请你设计时间复杂度为 O(n) 的算法解决本问题

解法1:暴力求解(平方后直接选择排序)

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int *sortedSquares(int *nums, int numsSize, int *returnSize)
{
    (*returnSize) = numsSize;
    int* ans = malloc(sizeof(int) * numsSize);
    for (int i = 0; i < numsSize; i++)
    {
        ans[i] = nums[i] * nums[i];
    }

    for (int i = 0; i < numsSize - 1; i++)
    {
        int minIndex = i;
        int swapTemp;
        for (int j = i + 1; j < numsSize; j++)
        {
            if (ans[j] < ans[minIndex])
            {
                minIndex = j;
            }
        }
        swapTemp = ans[i];
        ans[i] = ans[minIndex];
        ans[minIndex] =swapTemp;
    }
    return ans;
}

 解法2:双指针法

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int *sortedSquares(int *nums, int numsSize, int *returnSize)
{
    (*returnSize) = numsSize;
    int* ans = malloc(sizeof(int) * numsSize);
    for (int i = 0; i < numsSize; i++)
    {
        ans[i] = nums[i] * nums[i];
    }

    for (int i = 0; i < numsSize - 1; i++)
    {
        int minIndex = i;
        int swapTemp;
        for (int j = i + 1; j < numsSize; j++)
        {
            if (ans[j] < ans[minIndex])
            {
                minIndex = j;
            }
        }
        swapTemp = ans[i];
        ans[i] = ans[minIndex];
        ans[minIndex] =swapTemp;
    }
    return ans;
}

参考引用:代码随想录https://programmercarl.com/

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值