Problem:
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Now your job is to find the total Hamming distance between all pairs of the given numbers.
Example:
1 2 3 4 5 6 7 |
Input: 4, 14, 2 Output: 6 Explanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just showing the four bits relevant in this case). So the answer will be: HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6. |
Note:
- Elements of the given array are in the range of
0
to10^9
- Length of the array will not exceed
10^4
.
题目大意:给你一堆数,让你求所有数对的HammingDistance的总和。
Idea:
- Brute force, compute HammingDistance for all pairs. O(n^2) TLE
- Count how many ones on i-th bit, assuming k. Distance += k * (n – k). O(n)
Solution:
C++ / O(n)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
// Author: Huahua // Runtime: 59 ms class Solution { public: int totalHammingDistance(vector<int>& nums) { int ans = 0; int mask = 1; for (int i = 0; i < 32; ++i) { int count = 0; for (const int num : nums) if (num & mask) ++count; ans += (nums.size() - count) * count; mask <<= 1; } return ans; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment