代码:
public int[] sortedSquares(int[] nums) {
//三个指针,一个从左向右,一个从右向左,一个是目标数组从右向左
int leftPointer = 0;
int rightPointer = nums.length - 1;
int index = nums.length - 1;
//目标数组
int[] res = new int[nums.length];
//循环,从两边开始比较,将大的放入目标数组
while (leftPointer <= rightPointer) {
if (nums[leftPointer] * nums[leftPointer] < nums[rightPointer] * nums[rightPointer]) {
//右边的大
res[index] = nums[rightPointer] * nums[rightPointer];
rightPointer--;
} else {
//左边的大
res[index] = nums[leftPointer] * nums[leftPointer];
leftPointer++;
}
index--;
}
return res;
}