万事开头难
数组平方的最大值就在数组的两端,不可能在中间。所以考虑双指针法,left指向起始位置,right指向终止位置。
定义新数组result,与原数组一样大,让index指向终止位置
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* sortedSquares(int* nums, int numsSize, int* returnSize){
*returnSize = numsSize;
int left = 0;
int right = numsSize - 1;
int *array = (int *)malloc(sizeof(int) * numsSize); //定义新的数组
int index = 0;
for(index = numsSize - 1;index >= 0;index--)
{
if(nums[left]*nums[left] > nums[right] * nums[right]){
array[index] = nums[left] * nums[left];
left++;
}
else{
array[index] = nums[right] * nums[right];
right--;
}
}
return array;
}