# 977. 有序数组的平方(977. Square of ordered array)-其他

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

``````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;
}
}
``````