File tree 1 file changed +20
-17
lines changed
1 file changed +20
-17
lines changed Original file line number Diff line number Diff line change 1
1
/**
2
+ * Given an integer n, return an array ans of length n + 1 such that for each i
3
+ * (0 <= i <= n), ans[i] is the number of 1's in the binary representation of i.
4
+ *
5
+ * Constraints:
6
+ *
7
+ * 0 <= n <= 10^5
8
+ *
2
9
* Note: The returned array must be malloced, assume caller calls free().
10
+ *
11
+ * Space: O(1)
12
+ * Time: O(n)
3
13
*/
4
- int * countBits (int n , int * returnSize ){
5
- // Initialize array of size n + 1
6
- int arraySize = n + 1 ;
7
- * returnSize = arraySize ;
8
- int * dp = (int * )malloc (sizeof (int )* arraySize );
9
- memset (dp , 0 , arraySize * sizeof (dp [0 ]));
10
- int offset = 1 ;
11
-
12
- // Perform dp
13
- for (int i = 1 ; i <= n ; i ++ ) {
14
- if (offset * 2 == i ) {
15
- offset = i ;
16
- }
17
- dp [i ] = 1 + dp [i - offset ];
18
- }
19
- return dp ;
20
- }
14
+
15
+ int * countBits (int n , int * returnSize ) {
16
+ int * ret = calloc (n + 1 , sizeof (int ));
17
+ * returnSize = n + 1 ;
18
+
19
+ for (int i = 1 ; i <= n ; ++ i )
20
+ ret [i ] = ret [i >> 1 ] + (i & 1 );
21
+
22
+ return ret ;
23
+ }
You can’t perform that action at this time.
0 commit comments