-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathCountingBits.java
More file actions
112 lines (103 loc) · 2.86 KB
/
Copy pathCountingBits.java
File metadata and controls
112 lines (103 loc) · 2.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
/**
* <p>给你一个整数 <code>n</code> ,对于 <code>0 <= i <= n</code> 中的每个 <code>i</code> ,计算其二进制表示中 <strong><code>1</code> 的个数</strong> ,返回一个长度为 <code>n + 1</code> 的数组 <code>ans</code> 作为答案。</p>
*
* <p> </p>
*
* <div class="original__bRMd">
* <div>
* <p><strong>示例 1:</strong></p>
*
* <pre>
* <strong>输入:</strong>n = 2
* <strong>输出:</strong>[0,1,1]
* <strong>解释:</strong>
* 0 --> 0
* 1 --> 1
* 2 --> 10
* </pre>
*
* <p><strong>示例 2:</strong></p>
*
* <pre>
* <strong>输入:</strong>n = 5
* <strong>输出:</strong>[0,1,1,2,1,2]
* <strong>解释:</strong>
* 0 --> 0
* 1 --> 1
* 2 --> 10
* 3 --> 11
* 4 --> 100
* 5 --> 101
* </pre>
*
* <p> </p>
*
* <p><strong>提示:</strong></p>
*
* <ul>
* <li><code>0 <= n <= 10<sup>5</sup></code></li>
* </ul>
*
* <p> </p>
*
* <p><strong>进阶:</strong></p>
*
* <ul>
* <li>很容易就能实现时间复杂度为 <code>O(n log n)</code> 的解决方案,你可以在线性时间复杂度 <code>O(n)</code> 内用一趟扫描解决此问题吗?</li>
* <li>你能不使用任何内置函数解决此问题吗?(如,C++ 中的 <code>__builtin_popcount</code> )</li>
* </ul>
* </div>
* </div>
* <div><div>Related Topics</div><div><li>位运算</li><li>动态规划</li></div></div><br><div><li>👍 878</li><li>👎 0</li></div>
*/
package leetcode8;
public class CountingBits {
public static void main(String[] args) {
Solution solution = new CountingBits().new Solution();
}
/**
* DP
* if (奇数) DP( n ) = DP( n-1 ) + 1
* else DP( n ) = DP( n/2 )
* 优质题解:https://leetcode-cn.com/problems/counting-bits/solution/hen-qing-xi-de-si-lu-by-duadua/
*/
class Solution {
public int[] countBits(int n) {
int[] dp = new int[n + 1];
for (int i = 1; i <= n; i++) {
if (i % 2 == 1) {
dp[i] = dp[i - 1] + 1;
} else {
dp[i] = dp[i >> 1];
}
}
return dp;
}
}
class Solution2 {
public int[] countBits(int n) {
int[] res = new int[n + 1];
for (int i = 0; i <= n; i++) {
res[i] = counting(i);
}
return res;
}
private int counting(int n) {
int res = 0;
while (n != 0) {
res += n & 1;
n >>>= 1;
}
return res;
}
private int counting1(int n) {
int res = 0;
for (int i = 0; i < 32; i++) {
if ((n & (1 << i)) != 0) {
res++;
}
}
return res;
}
}
}