Skip to content

Commit 8a35955

Browse files
添加 0977.有序数组的平方.md C语言版本
1 parent 6886111 commit 8a35955

File tree

1 file changed

+32
-1
lines changed

1 file changed

+32
-1
lines changed

problems/0977.有序数组的平方.md

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -270,7 +270,38 @@ def sorted_squares(nums)
270270
end
271271
```
272272

273-
273+
C:
274+
```c
275+
int* sortedSquares(int* nums, int numsSize, int* returnSize){
276+
//返回的数组大小就是原数组大小
277+
*returnSize = numsSize;
278+
//创建两个指针,right指向数组最后一位元素,left指向数组第一位元素
279+
int right = numsSize - 1;
280+
int left = 0;
281+
282+
//最后要返回的结果数组
283+
int* ans = (int*)malloc(sizeof(int) * numsSize);
284+
int index;
285+
for(index = numsSize - 1; index >= 0; index--) {
286+
//左指针指向元素的平方
287+
int lSquare = nums[left] * nums[left];
288+
//右指针指向元素的平方
289+
int rSquare = nums[right] * nums[right];
290+
//若左指针指向元素平方比右指针指向元素平方大,将左指针指向元素平方放入结果数组。左指针右移一位
291+
if(lSquare > rSquare) {
292+
ans[index] = lSquare;
293+
left++;
294+
}
295+
//若右指针指向元素平方比左指针指向元素平方大,将右指针指向元素平方放入结果数组。右指针左移一位
296+
else {
297+
ans[index] = rSquare;
298+
right--;
299+
}
300+
}
301+
//返回结果数组
302+
return ans;
303+
}
304+
```
274305
275306
-----------------------
276307
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)

0 commit comments

Comments
 (0)