C语言——双指针法求有序数组的平方
代码
#include <stdio.h>
#include <stdlib.h>
int* sortedSquares(int* nums, int numsSize)
{
int left = 0;
int right = numsSize - 1;
int* ans = (int*)malloc(sizeof(int) * numsSize);
int index;
for (index = numsSize - 1; index >= 0; index--)
{
int lsquare = nums[left] * nums[left];
int rsquare = nums[right] * nums[right];
if (lsquare > rsquare)
{
ans[index] = lsquare;
left++;
}
else
{
ans[index] = rsquare;
right--;
}
}
for (int i = 0; i < numsSize; i++)
{
printf("%d ", ans[i]);
}
free(ans);
}
int main()
{
int numsSize;
scanf_s("%d", &numsSize);
int* nums = (int*)malloc(sizeof(int) * numsSize);
if (nums == NULL)
{
return 1;
}
else
{
for (int i = 0; i < numsSize; i++)
{
scanf_s("%d", nums + i);
}
}
sortedSquares(nums, numsSize);
free(nums);
return 0;
}
结果