如何在时间复杂度为O(n)的约束下,让有序数组的平方也为有序数组
class Solution {
public int[] sortedSquares(int[] nums) {
int start = 0;
int end = nums.length-1;
int temp[] = new int[end+1];
int len = end;
while(start<=end){
int a = pow(nums[start]);
int b = pow(nums[end]);
if(a<b){
temp[len]=b;
end--;
}else{
temp[len] = a;
start++;
}
len--;
}
return temp;
}
public int pow(int x){
return x*x;
}
}
测试用例为:[-4,-1,0,3,10]
我们可以注意到,测试用例是非递减的数组,因此平方最大值只可能是两端,我们通过创建与nums相同长度的数组temp,建立start和end指针,判断两端数组元素平方的大小,将大的放入到temp数组末端,然后len-1,len为temp数组的当前下标。然后进行下一次比较,若左端元素较大,则start+1继续与end比较,若右端元素较大,则end-1继续与start比较,依次往复直到start>end即为终止条件。