这个问题我卡了很久,我一直想的是从中间拆分数组,但是遇到那种不对称的数组,就无法执行,
下面是别人的代码,它的主要思路是,首先在数组两边建立两个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;
}
}

博主曾卡在从中间拆分数组的问题上,遇到不对称数组无法执行。他人代码思路是在数组两边建立index,比较绝对值大小,因原数组递减,绝对值最大值在两边,先确定result数组最右边数字,再将index向中间移动,每次比较后放入较大值,两index相遇时找到最小值。
882

被折叠的 条评论
为什么被折叠?



