Skip to content

Commit 2a0326a

Browse files
committed
LC#338 optimal, returns array containting bit counts, O(N) time, O(N) Space
1 parent 17c9aa7 commit 2a0326a

File tree

1 file changed

+21
-6
lines changed

1 file changed

+21
-6
lines changed

Leetcode/easy/CountingBits338.java

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -26,15 +26,30 @@ private static int countBinaryOnes(int num) {
2626
return count;
2727
}
2828

29+
// optimal code using DP
30+
public static int[] countBitsDP(int n) {
31+
int[] ans = new int[n + 1];
32+
ans[0] = 0;
33+
34+
for (int index = 1; index <= n; index++) {
35+
if (index % 2 == 0) { // even
36+
ans[index] = ans[index / 2];
37+
} else { // odd
38+
ans[index] = 1 + ans[index / 2];
39+
}
40+
}
41+
return ans;
42+
}
43+
2944
public static void main(String[] args) {
3045
System.out.println(Arrays.toString(countBits(2)));
3146
System.out.println(Arrays.toString(countBits(5)));
3247
System.out.println(Arrays.toString(countBits(0)));
48+
49+
System.out.println("\noptimal\n");
50+
51+
System.out.println(Arrays.toString(countBitsDP(2)));
52+
System.out.println(Arrays.toString(countBitsDP(5)));
53+
System.out.println(Arrays.toString(countBitsDP(0)));
3354
}
3455
}
35-
36-
/* output:
37-
[0, 1, 1]
38-
[0, 1, 1, 2, 1, 2]
39-
[0]
40-
*/

0 commit comments

Comments
 (0)