思路:因为原来的数组是有序的,数组平方以后的最大值一定是在原来数组的最左边或者最右边,所以在原数组两端设置两个指针,比较指针所指的数的平方大小,将值较大的放到result数组里,移动指针继续比较直到两个指针相遇。
class Solution {
public int[] sortedSquares(int[] nums) {
//left指针指向最左边的数
int left = 0;
//right指针指向最右边的数
int right = nums.length - 1;
//index指针指向result数组的最右边的位置
int index = nums.length - 1;
//result数组用于放置排序好的结果
int[] result = new int[nums.length];
//如果left和right指针没有相遇,就继续比较下去
while (left <= right){
//比较left指针和right指针指向的数的平方大小,如果左边的数的平方比较大
if(nums[left] * nums[left] > nums[right] * nums[right]){
//那么把这个平方数放到result数组,result数组是从最右边开始放的
result[index] = nums[left] * nums[left];
//左边的一个数放到了结果数组,left向右移动
left++;
//result数组的指针index向左移动
index--;
}else {//如果右边的数的平方比较大
//那么把这个平方数放到result数组
result[index] = nums[right] * nums[right];
//right指针向左移动
right--;
//result数组的指针index向左移动
index--;
}
}
//将result数组返回
return result;
}
}