这个问题我卡了很久,我一直想的是从中间拆分数组,但是遇到那种不对称的数组,就无法执行,
下面是别人的代码,它的主要思路是,首先在数组两边建立两个index,然后通过比较绝对值大小,由于原数组是递减,所以绝对值的最大值一定出现在两边,这样对result数组中最右边数字就可以先定下来,然后将两个index向中间移动,每次比较后将较大的值放入result数组中,当两个index相遇,则找到最小值。
class Solution {
public int[] sortedSquares(int[] nums) {
int left = 0 ;
int right = nums.length-1;
int[] result = new int[nums.length];
int idx = nums.length - 1;
while(left <= right)
{
if(Math.abs(nums[left]) > nums[right])
{
result[idx--] = nums[left] * nums[left];
left++;
}
else
{
result[idx--] = nums[right] * nums[right];
right--;
}
}
return result;
}
}