# Question

Formatted question description: https://leetcode.ca/all/977.html

```
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].
Example 2:
Input: nums = [-7,-3,2,3,11]
Output: [4,9,9,49,121]
Constraints:
1 <= nums.length <= 104
-104 <= nums[i] <= 104
nums is sorted in non-decreasing order.
```

# Algorithm 1

This question gives an array in non-descending order, which can have negative numbers. Now let’s find the square of each number, and it is also in non-descending order. If there are only positive numbers in the array, the order of the squared array and the original array is still the same. But if the square of a negative number is a positive number, the order will be disrupted.

The simplest method is to store the square number in a TreeSet, and use its automatic sorting function to get the desired order. Note that you need to use multiset here because there may be duplicate values. See the code below:

# Code 1

C++

# Algorithm 2

If you want to further optimize the time complexity, you can use double pointers to do it, use two variables to point to the beginning and the end, and then compare, each time the square value of the number with the larger absolute value is added to the end of the array first, and then Update one by one, the final result is the requested order, see the code as follows:

# Code 2

C++

Java

```
class Solution {
public int[] sortedSquares(int[] A) {
if (A == null || A.length == 0)
return A;
int length = A.length;
int minAbs = Integer.MAX_VALUE;
int startIndex = -1;
for (int i = 0; i < length; i++) {
int num = A[i];
int abs = Math.abs(num);
if (abs < minAbs) {
minAbs = abs;
startIndex = i;
}
if (num > minAbs)
break;
}
int[] squares = new int[length];
squares[0] = minAbs * minAbs;
int index = 1;
int index1 = startIndex - 1, index2 = startIndex + 1;
while (index1 >= 0 && index2 < length) {
if (Math.abs(A[index1]) <= Math.abs(A[index2])) {
squares[index] = A[index1] * A[index1];
index1--;
} else {
squares[index] = A[index2] * A[index2];
index2++;
}
index++;
}
while (index1 >= 0) {
squares[index] = A[index1] * A[index1];
index++;
index1--;
}
while (index2 < length) {
squares[index] = A[index2] * A[index2];
index++;
index2++;
}
return squares;
}
}
```