【Leetcode】[977] 有序数组的平方

这篇博客介绍了如何用双指针技巧解决LeetCode上的977题,即给定一个非递减排序的整数数组,返回每个数字的平方组成的非递减排序数组。作者提供了三种不同的解决方案,虽然执行时间有所不同,但都利用了数组的有序性。通过比较平方值,从两端向中间遍历,实现了平方运算并保持排序。

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

【Leetcode】[977] 有序数组的平方

Author: Xin Pan

Date: 2022.3.2


题目

原题链接

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

解法

由于题目输入是排序数组。这个时候可以考虑使用双指针技巧来解题。

答案1

执行用时: 20 ms 内存消耗: 26.4 MB

class Solution
{
public:
    vector<int> sortedSquares(vector<int> &nums)
    {
        int nnum = nums.size();
        vector<int> vecret(nnum);
        int nl = 0, nr = nnum - 1, ind = nnum - 1;
        while (nl <= nr)
        {
            if (nums[nl] * nums[nl] <= nums[nr] * nums[nr])
            {
                vecret[ind--] = pow(nums[nr--], 2);
            }
            else
            {
                vecret[ind--] = pow(nums[nl++], 2);
            }
        }
        return vecret;
    }
};

答案2

执行用时: 24 ms 内存消耗: 25.1 MB

class Solution
{
public:
    vector<int> sortedSquares(vector<int> &nums)
    {
        int nnum = nums.size();
        vector<int> vecret(nnum);
        int nl = 0, nr = nnum - 1, ind = nnum - 1;
        while (nl <= nr)
        {
            if (nums[nl] * nums[nl] <= nums[nr] * nums[nr])
            {
                vecret[ind--] = nums[nr] * nums[nr];
                nr--;
            }
            else
            {
                vecret[ind--] = nums[nl] * nums[nl];
                nl++;
            }
        }
        return vecret;
    }
};

答案3

执行用时: 32 ms 内存消耗: 25.3 MB

class Solution
{
public:
    vector<int> sortedSquares(vector<int> &nums)
    {
        int nnum = nums.size();
        vector<int> vecret(nnum);
        int nl = 0, nr = nnum - 1, ind = nnum - 1;
        while (nl <= nr)
        {
            if (nums[nl] * nums[nl] <= nums[nr] * nums[nr])
            {
                vecret[ind--] = pow(nums[nr--], 2);
            }
            else
            {
                vecret[ind--] = pow(nums[nl++], 2);
            }
        }
        return vecret;
    }
};

越写时间消耗越大,看起来花里胡哨的,都是虚的。真淦。越写越差就是我了,无疑了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值