首页 > 试题广场 >

平方升序数组

[编程题]平方升序数组
  • 热度指数:1250 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
给定一个长度为 n 的升序数组 nums ,请你算出这个数组中所有数的平方组成的新的数组,要求也按照升序。

数据范围: ,数组中的数都满足
示例1

输入

[1,0,1,2,3]

输出

[0,1,1,4,9]
示例2

输入

[5,4,3,2,1]

输出

[1,4,9,16,25]
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param nums int整型一维数组 
 * @param numsLen int nums数组长度
 * @return int整型一维数组
 * @return int* returnSize 返回数组行数
 */
int comp(const void*a,const void*b)
{
    if((*(int*)a)<0)
        (*(int*)a)=-(*(int*)a);
    if((*(int*)b)<0)
         (*(int*)b)=-(*(int*)b);
return *(int*)a-*(int*)b;
}
int* sortedArray(int* nums, int numsLen, int* returnSize ) {
    // write code here
    qsort(nums,numsLen,sizeof(int),comp);
    int *ans=(int *)malloc(sizeof(int)*numsLen);
    for(int i=0;i<numsLen;i++){
        ans[i]=nums[i]*nums[i];
    }
    *returnSize=numsLen;
    return ans;
}

发表于 2022-12-24 10:35:24 回复(0)