File tree Expand file tree Collapse file tree 1 file changed +75
-0
lines changed
problems/477. Total Hamming Distance Expand file tree Collapse file tree 1 file changed +75
-0
lines changed Original file line number Diff line number Diff line change
1
+ # 477. Total Hamming Distance
2
+
3
+ ## #1 暴力搜索+位操作[ TLE]
4
+
5
+ ### 思路
6
+
7
+ 之前做过求解两个数Hamming Distance的题目,这个题目在数据维度进行扩展,从两个数扩展至多个数,要求这些所有的数海明距离之和。最直接的想法就是遍历所有的数值对,然后求它们的海明距离,并每个海明距离都加入到结果中。
8
+
9
+ ### 算法
10
+
11
+ ``` java
12
+ class Solution {
13
+ public int totalHammingDistance (int [] nums ) {
14
+ if (nums == null || nums. length == 0 )
15
+ return 0 ;
16
+ int res = 0 ;
17
+ for (int i= 0 ; i< nums. length- 1 ; i++ ){
18
+ for (int j= i+ 1 ; j< nums. length; j++ )
19
+ res += hammingDistance(nums[i], nums[j]);
20
+ }
21
+ return res;
22
+ }
23
+
24
+ public int hammingDistance (int x , int y ) {
25
+ return bitCount(x ^ y);
26
+ }
27
+
28
+ public int bitCount (int num ){
29
+ int count = 0 ;
30
+ while (num != 0 ){
31
+ num &= (num- 1 );
32
+ count++ ;
33
+ }
34
+ return count;
35
+ }
36
+ }
37
+ ```
38
+
39
+ ### 复杂性分析:
40
+
41
+ - 时间复杂性:$O(32* n^2)$
42
+ - 空间复杂性:$O(1)$
43
+
44
+ ## #2 优化位操作[ AC]
45
+
46
+ ### 思路
47
+
48
+ 我们可以统计在每个bit set上为1的数值个数有多少,假设统计出在第i位为1的数值个数有` k ` 个,那么在第i位为0的数值个数就有` n-k ` 个。那么第i位,对最终的海明距离的贡献值就是` k*(n-k) ` 。对于每个bit set,统计其贡献值,即可得到最终的结果。
49
+
50
+ ### 算法
51
+
52
+ ``` java
53
+ class Solution {
54
+ public int totalHammingDistance (int [] nums ) {
55
+ if (nums == null || nums. length == 0 )
56
+ return 0 ;
57
+ int n = nums. length;
58
+ int total = 0 ;
59
+ for (int i= 0 ; i< 32 ; i++ ){ // loop for all bit set
60
+ int bitCount = 0 ;
61
+ for (int j= 0 ; j< n; j++ ){// loop for all number
62
+ bitCount += (nums[j] >> i) & 1 ;
63
+ }
64
+ total += bitCount * (n - bitCount);
65
+ }
66
+ return total;
67
+ }
68
+ }
69
+ ```
70
+
71
+ ### 复杂性分析:
72
+
73
+ - 时间复杂性:$O(n^2)$
74
+ - 空间复杂性:$O(1)$
75
+
You can’t perform that action at this time.
0 commit comments