977. 有序数组的平方(977. Square of ordered 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]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/squares-of-a-sorted-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

class Solution {
    public int[] sortedSquares(int[] nums) {
        if (nums == null || nums.length == 0) {
            return new int[0];
        }
        int[] ans = new int[nums.length];
        int left = 0, right = nums.length - 1;
        while (left <= right) {
            int leftPow = nums[left] * nums[left];
            int rightPow = nums[right] * nums[right];
            int index = right - left;
            if (leftPow < rightPow) {
                ans[index] = rightPow;
                right--;
            } else {
                ans[index] = leftPow;
                left++;
            }
        }
        return ans;
    }
}
————————

Give you an integer array nums sorted in non decreasing order, and return a new array composed of the square of each number. It is also required to sort in non decreasing order.

Example 1:

Input: num = [- 4, – 1,0,3,10]
Output: [0,1,9,16100]
Explanation: after squaring, the array becomes [16,1,0,9100]
After sorting, the array becomes [0,1,9,16100]
Example 2:

Input: num = [- 7, – 3,2,3,11]
Output: [4,9,9,49121]

Source: leetcode
Link: https://leetcode-cn.com/problems/squares-of-a-sorted-array
The copyright belongs to Lingkou network. For commercial reprint, please contact the official authorization, and for non-commercial reprint, please indicate the source.

class Solution {
    public int[] sortedSquares(int[] nums) {
        if (nums == null || nums.length == 0) {
            return new int[0];
        }
        int[] ans = new int[nums.length];
        int left = 0, right = nums.length - 1;
        while (left <= right) {
            int leftPow = nums[left] * nums[left];
            int rightPow = nums[right] * nums[right];
            int index = right - left;
            if (leftPow < rightPow) {
                ans[index] = rightPow;
                right--;
            } else {
                ans[index] = leftPow;
                left++;
            }
        }
        return ans;
    }
}