思想是:因为数组本身就是有序的,所以最大值的平方一定在数组的最两端,对这两端的值进行比较,定义一个新数组,谁大谁就放入新数组的最后面,并对游标值减一,上边如果是left大那就left+1,如果是right大,那就right-1,这样新数组就会是有序数组的平方的结果。
class Solution {
public int[] sortedSquares(int[] nums) {
int right = nums.length - 1;
int left = 0;
int[] result = new int[nums.length];
int index = result.length - 1;
while (left <= right) {
if (nums[left] * nums[left] > nums[right] * nums[right]) {
// 正数的相对位置是不变的, 需要调整的是负数平方后的相对位置
result[index--] = nums[left] * nums[left];
++left;
} else {
result[index--] = nums[right] * nums[right];
--right;
}
}
return result;
}
}