977.有序数组的平方

给你一个按 非递减顺序 排序的整数数组 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] 力扣题目链接

 

code:

  我的思路是先找到一个左邻是负数,右邻是非负数的两个位置,然后比较这两个位置,把小的插入到新数组的末尾,直到将所有的数都插入。

  但是实现的时候,发现并不容易实现,相较于双指针从首尾往中间汇合,首先要考虑只有一个元素的情况,此时并不存在右邻,所以溢出,其次要考虑全为负数的时候,此时右邻也是溢出的。所以总共分为三种情况。

复制代码
#include<vector>
#include <iostream>
using namespace std;

class Solution {
public:
    vector<int> sortedSquares(vector<int>& nums) {
        int i, j;
        vector<int> res;
        if (nums.size() == 1)//此时只有一个元素
        {
            nums[0] = nums[0] * nums[0];
            res.insert(res.end(), nums[0]);
            return res;
        }
        for(i = 0; i < nums.size()-1; i++)
        {
            j = i + 1;
            if (nums[i] < 0 && nums[j] >= 0)
            {
                break;
            }
        }
        if (nums[j] < 0)//此时全为负数
        {
            for (j; j >= 0; j--)
            {
                nums[j] = nums[j] * nums[j];
                res.insert(res.end(), nums[j]);
            }
            return res;
        }
        if (i >= 0 && nums[0] < 0)
        {
            int b = i + 1;
            for (int a = i; a >= 0; a--)
            {
                nums[a] = nums[a] * (-1);
                while(b<= nums.size() - 1 && nums[b] <= nums[a])
                {
                    res.insert(res.end(), nums[b++]);
                }
                res.insert(res.end(), nums[a]);
            }
            while (b < nums.size())
            {
                res.insert(res.end(), nums[b++]);
            }
            for (auto& c : res)
            {
                c = c * c;
            }
            return res;
        }
        else {
            for (auto& c : nums)
            {
                c = c * c;
                res.insert(res.end(), c);
            }
            return res;
        }
        
            
    }
};
int main() {
    vector<int> nums = { 0,2 };
    vector<int> res;
    Solution a;
    res = a.sortedSquares(nums);
    for (const auto c : res)
    {
        cout<< c<<" ";
    }
}
复制代码

 

标准答案:

  

复制代码
class Solution {
public:
    vector<int> sortedSquares(vector<int>& A) {
        int k = A.size() - 1;
        vector<int> result(A.size(), 0);
        for (int i = 0, j = A.size() - 1; i <= j;) { // 注意这里要i <= j,因为最后要处理两个元素
            if (A[i] * A[i] < A[j] * A[j])  {
                result[k--] = A[j] * A[j];
                j--;
            }
            else {
                result[k--] = A[i] * A[i];
                i++;
            }
        }
        return result;
    }
};
复制代码

 

posted @   xiazichengxi  阅读(19)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
点击右上角即可分享
微信分享提示
主题色彩