Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 84f41f6

Browse files
添加 0135.分发糖果.md C语言解法
1 parent 1adb662 commit 84f41f6

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

‎problems/0135.分发糖果.md‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -238,6 +238,47 @@ var candy = function(ratings) {
238238
};
239239
```
240240

241+
### C
242+
```c
243+
#define max(a, b) (((a) > (b)) ? (a) : (b))
244+
245+
int *initCandyArr(int size) {
246+
int *candyArr = (int*)malloc(sizeof(int) * size);
247+
248+
int i;
249+
for(i = 0; i < size; ++i)
250+
candyArr[i] = 1;
251+
252+
return candyArr;
253+
}
254+
255+
int candy(int* ratings, int ratingsSize){
256+
// 初始化数组,每个小孩开始至少有一颗糖
257+
int *candyArr = initCandyArr(ratingsSize);
258+
259+
int i;
260+
// 先判断右边是否比左边评分高。若是,右边孩子的糖果为左边孩子+1(candyArr[i] = candyArr[i - 1] + 1)
261+
for(i = 1; i < ratingsSize; ++i) {
262+
if(ratings[i] > ratings[i - 1])
263+
candyArr[i] = candyArr[i - 1] + 1;
264+
}
265+
266+
// 再判断左边评分是否比右边高。
267+
// 若是,左边孩子糖果为右边孩子糖果+1/自己所持糖果最大值。(若糖果已经比右孩子+1多,则不需要更多糖果)
268+
// 举例:ratings为[1, 2, 3, 1]。此时评分为3的孩子在判断右边比左边大后为3,虽然它比最末尾的1(ratings[3])大,但是candyArr[3]为1。所以不必更新candyArr[2]
269+
for(i = ratingsSize - 2; i >= 0; --i) {
270+
if(ratings[i] > ratings[i + 1])
271+
candyArr[i] = max(candyArr[i], candyArr[i + 1] + 1);
272+
}
273+
274+
// 求出糖果之和
275+
int result = 0;
276+
for(i = 0; i < ratingsSize; ++i) {
277+
result += candyArr[i];
278+
}
279+
return result;
280+
}
281+
```
241282
242283
-----------------------
243284
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /