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 40a68aa

Browse files
AC 338
1 parent 7daceba commit 40a68aa

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

‎c/300-399/338-counting-bits.c‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/*
2+
* Copyright (C) 2022, Saul Lawliet <october dot sunbathe at gmail dot com>
3+
* All rights reserved.
4+
*
5+
* Follow up:
6+
* - It is very easy to come up with a solution with a runtime of O(n log n). Can you do it in linear time O(n) and possibly in a single pass?
7+
*
8+
* 如果是 O(n) 的时间复杂度, 那么思考方向应该类似于动态规划的做法
9+
* PS: 尝试引入变量, 来减少循环中的计算, 但效果不明显, 可能原因是: 相同的代码每次执行的时候可能会有不同的运行时间
10+
*/
11+
12+
#include "c/data-structures/array.h"
13+
#include "c/test.h"
14+
15+
/**
16+
* Note: The returned array must be malloced, assume caller calls free().
17+
*/
18+
int *countBits(int n, int *returnSize) {
19+
*returnSize = n + 1;
20+
int *returnArray = malloc(sizeof(int) * *returnSize);
21+
returnArray[0] = 0;
22+
if (n >= 1) returnArray[1] = 1;
23+
int pow = 4;
24+
for (int i = 2; i < *returnSize; i++) {
25+
if (i < pow) {
26+
returnArray[i] = 1 + returnArray[i - pow / 2];
27+
} else {
28+
returnArray[i] = 1;
29+
pow <<= 1;
30+
}
31+
}
32+
return returnArray;
33+
}
34+
35+
void test(const char *expect, int n) {
36+
int returnSize;
37+
int *returnArray = countBits(n, &returnSize);
38+
39+
EXPECT_EQ_STRING_AND_FREE_ACTUAL(expect, arrayToString1D(returnArray, returnSize, ARRAY_INT));
40+
}
41+
42+
int main(void) {
43+
test("[0,1,1]", 2);
44+
test("[0,1,1,2,1,2]", 5);
45+
46+
return testOutput();
47+
}

0 commit comments

Comments
(0)

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