meta data for this page
  •  

Squares of a Sorted Array

Leetcode


Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.

Example 1:

Input: nums = [-4,-1,0,3,10]
Output: [0,1,9,16,100]
Explanation: After squaring, the array becomes [16,1,0,9,100].
After sorting, it becomes [0,1,9,16,100].

Solution 1

Solution 1

public int[] sortedSquares(int[] nums) {
  int[] output = new int[nums.length];
  int l = 0, r = nums.length - 1;
  int idx = r;
 
  while (l <= r) {
    int lv = nums[l] * nums[l];
    int rv = nums[r] * nums[r];
 
    if (lv > rv) {
      output[idx--] = lv;
      l++;
    } else {
      r--;
      output[idx--] = rv;
    }
  }
  return output;
}