题目内容

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

事例

输入:nums = [-4,-1,0,3,10]
输出:[0,1,9,16,100]
解释:平方后,数组变为 [16,1,0,9,100]
排序后,数组变为 [0,1,9,16,100]

代码实现

方式①:双指针

class Solution {
   
    public int[] sortedSquares(int[] nums) {
   
        if (nums == null || nums.length == 0) {
   
            throw new RuntimeException("illegal parameter!");
        }
        int len = nums.length;
        //新建一个数组
        int[] ans = new int[len];  
        //left表示指向左边元素的下标,right表示指向右边元素的下标,pos表示ans数组的下标
        for (int left = 0, right = len - 1, pos = len - 1; left <= right; ) {
   
            if (nums[left] * nums[left] > nums[right] * nums[right]) {
   
                ans[pos] = nums[left] * nums[left];
                left++;
            }else {
   
                ans[pos] = nums[right] * nums[right];
                right--;
            }
            pos--;
        }
        return ans;
        
    }
}

方法②:使用Arrays.sort()静态方法,底层使用快速排序

class Solution {
   
    public int[] sortedSquares(int[] nums) {
   
        if (nums == null || nums.length == 0) {
   
            throw new RuntimeException("illegal parameter!");
        }

        //对所有元素进行平方
        for (int i = 0; i <= nums.length - 1; i++) {
   
            nums[i] = (int) Math.pow(nums[i], 2);
        }
        //重新排序
        Arrays.sort(nums);
        return nums;
        
    }
}