leetcode 977. Squares of a Sorted Array

本文介绍了一种基于快速排序算法的实现,并在此基础上完成了一个特殊的排序任务:对输入数组中的每个元素进行平方操作后再排序。该算法首先通过快速排序对平方后的数组进行排序,确保了即使输入数组包含负数也能正确输出按平方值大小排列的结果。

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

#include<vecor>
class Solution {
public:
    void quick_sort(vector<int> &num, int low1, int high1)
    {
        int tmp = num[low1];
        int low = low1,high = high1;
        if(low>=high) return;
        while(low<high)
        {
            while(low<high&&num[high]>=tmp)
            {
                high --;
            }
            if(low <high)
            {
                int t = num[low];
                num[low] =num[high];
                num[high] = t;
                low ++;
            }
            while(low<high&&num[low]<=tmp)
            {
              low ++;
            }
            if(low<high)
            {
                int t = num[low];
                num[low] =num[high];
                num[high] = t;
                high --;
            }

          
       }
        num[low] = tmp;
        quick_sort(num,low1,low-1);
       quick_sort(num,low+1,high1);
    }
    vector<int> sortedSquares(vector<int>& A) {
        vector<int> num;
        int l = A.size();
        for(int i=0;i<l;i++)
        {
            num.push_back(A[i]*A[i]);
         }
        quick_sort(num,0,l-1);
        return num;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值