数组 - 977. 有序数组的平方(C#和C实现)
题目描述
给定一个按照升序排列的整数数组 nums
,返回每个数字的平方组成的新数组,要求也按照升序排列。
解题思路
由于数组已经按照升序排列,我们可以利用双指针的方法,分别从数组的两端开始遍历,比较平方后的值大小,然后将较大的平方值放入结果数组的末尾。这样可以保证结果数组是按照升序排列的。
解题步骤
-
初始化结果数组
result
,长度与输入数组nums
相同。 -
使用两个指针
left
和right
分别指向数组nums
的开始和结束位置。 -
循环遍历数组,比较
nums[left]和 nums[right]的平方值大小:
- 如果
nums[left]
的平方值大于等于nums[right]
的平方值,将nums[left]
的平方值放入result
数组的末尾,然后左指针向右移动一位。 - 如果
nums[left]
的平方值小于nums[right]
的平方值,将nums[right]
的平方值放入result
数组的末尾,然后右指针向左移动一位。
- 如果
-
返回结果数组
result
。
特殊案例
- 如果输入数组为空,则直接返回空数组 []。
C#代码实现
public int[] SortedSquares(int[] nums) {
int[] result = new int[nums.Length];
int left = 0;
int right = nums.Length - 1;
int index = nums.Length - 1;
while (left <= right) {
int leftSquare = nums[left] * nums[left];
int rightSquare = nums[right] * nums[right];
if (leftSquare >= rightSquare) {
result[index] = leftSquare;
left++;
} else {
result[index] = rightSquare;
right--;
}
index--;
}
return result;
}
C代码实现
int* sortedSquares(int* nums, int numsSize, int* returnSize) {
int* result = (int*)malloc(sizeof(int) * numsSize);
int left = 0, right = numsSize - 1, index = numsSize - 1;
while (left <= right) {
int leftSquare = nums[left] * nums[left];
int rightSquare = nums[right] * nums[right];
if (leftSquare >= rightSquare) {
result[index] = leftSquare;
left++;
} else {
result[index] = rightSquare;
right--;
}
index--;
}
*returnSize = numsSize;
return result;
}
时间复杂度和空间复杂度
- 时间复杂度:O(n),其中 n 是数组
nums
的长度。遍历一次数组。 - 空间复杂度:O(1)。除了保存结果的数组之外,算法的空间复杂度是常数级别的。
参与点评
读者朋友们,如果您在阅读过程中,对文章的质量、易理解性有任何建议,欢迎在评论区指出,我会认真改进。