力扣977. 有序数组的平方(双指针、归并)

力扣977. 有序数组的平方(双指针、归并)

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

示例 1:

输入:[-4,-1,0,3,10]
输出:[0,1,9,16,100]
示例 2:

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

提示:

1 <= A.length <= 10000
-10000 <= A[i] <= 10000
A 已按非递减顺序排序。

 

双指针、归并

思路:

  1. 利用已排序的特点,找到负数与非负的分界线pos
  2. pos两边,左右双指针left和right
  3. 归并排序

复杂度分析

  • 时间复杂度:O(n),其中 n 是数组 A 的长度。

  • 空间复杂度:O(1)。

#include <iostream>
#include<vector>
#include <math.h>
using namespace std;
class Solution {
public:
    vector<int> sortedSquares(vector<int>& A) {
        int n=A.size();
        vector<int> result;
        if(n==0)return result;
        //先找出绝对值最少的那一个,分界线
        int pos=0;
        for (int i=1; i<n; i++) {
            if (abs(A[i])<abs(A[i-1])) {
                pos=i;
            }
        }
        int left=pos-1;
        int right=pos+1;
        result.push_back(pow(A[pos],2));
        //归并排序
        while (left>=0 && right<=n-1) {
            int leftpow=pow(A[left],2);
            int rightpow=pow(A[right],2);
            if (leftpow>=rightpow) {
                result.push_back(rightpow);
                right++;
            }
            if (leftpow<rightpow) {
                result.push_back(leftpow);
                left--;
            }
        }
        
        while (left>=0) {
            int leftpow=pow(A[left],2);
                result.push_back(leftpow);
                left--;
        }
        
        while (right<=n-1) {
            int rightpow=pow(A[right],2);
            result.push_back(rightpow);
            right++;
        }
        
        return result;
    }
};
int main(int argc, const char * argv[]) {
    // insert code here...
    vector<int>A;A.push_back(-4);A.push_back(-1);A.push_back(0);A.push_back(3);A.push_back(10);
    Solution s;
    auto result=s.sortedSquares(A);
    for (int i=0; i<result.size(); i++) {
        std::cout <<result[i]<<"  ";
    }
    std::cout << "\nHello, World!\n";
    return 0;
}

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值