有序数组的平方

此博客链接:

有序数组的平方

题链链接:https://leetcode-cn.com/problems/squares-of-a-sorted-array/

题目

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

题解

这题的难点在于如何在平方后对新的数组进行排序,使用双指针对平方后的数组进行排序比较方便,还有有效,由于最大的数和负数绝对值最大的数在数组的两端,所以只需要比较数组两端的数那个大,那个大就放到结果数组的最后。

代码

class Solution {
    public int[] sortedSquares(int[] nums) {
    int len=nums.length;
    int res[]=new int[len];
    int i=0;
    int j=nums.length-1;
    while(len>0){
        if(nums[i]*nums[i]>nums[j]*nums[j])
        {
                 
           res[len-1]=nums[i]*nums[i];
       i++;
        }
        else {
            res[len-1]=nums[j]*nums[j];
                    j--;
     
        }
        len--;
    }
    return res;
    }
}

 

结果

 

posted @ 2021-07-20 12:56  萍2樱释  阅读(55)  评论(0编辑  收藏  举报