From 8a35955a04594b22d6ea07af06188580a5c6c9f4 Mon Sep 17 00:00:00 2001 From: ArthurP Date: Thu, 2 Sep 2021 12:33:00 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200977.=E6=9C=89=E5=BA=8F?= =?UTF-8?q?=E6=95=B0=E7=BB=84=E7=9A=84=E5=B9=B3=E6=96=B9.md=20C=E8=AF=AD?= =?UTF-8?q?=E8=A8=80=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0977.有序数组的平方.md | 31 ++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/problems/0977.有序数组的平方.md b/problems/0977.有序数组的平方.md index 13142853..089884fc 100644 --- a/problems/0977.有序数组的平方.md +++ b/problems/0977.有序数组的平方.md @@ -270,7 +270,38 @@ def sorted_squares(nums) end ``` +C: +```c +int* sortedSquares(int* nums, int numsSize, int* returnSize){ + //返回的数组大小就是原数组大小 + *returnSize = numsSize; + //创建两个指针,right指向数组最后一位元素,left指向数组第一位元素 + int right = numsSize - 1; + int left = 0; + //最后要返回的结果数组 + 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--; + } + } + //返回结果数组 + return ans; +} +``` ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)