問題:
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: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 to 10^9
- Length of the array will not exceed 10^4.
大意:
兩個整數之間的Hamming distance是指它們在二進制表示上各個位的數不同的個數。
現在你的工作是找出每對數字之間的Hamming distance的總和。
例子:
輸入:4, 14, 2
輸出:6
解釋:在二進制表示法中,4是 0100,14是 1110,2是 0010(這里只顯示四位)。所以答案應該是 HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6。
注意:
- 給出的元素范圍在0到10的9次方。
- 數組的長度不會超過10的4次方。
思路:
這里如果使用雙重循環一個個比較兩個數字的差異,可以算出來,但是在時間上會有用例超時。
這里換一種思路,我們看每個數都有32位,對每一位,我們統計數組中的數再這一位上為1的有幾個數,那么在這一位上,所有兩對數不同的情況是為1的數量乘以為0的數量,是個排列組合的問題。對每一位我們都這樣操作,就可以很快得出結果了。
代碼(Java):
public class Solution {
public int totalHammingDistance(int[] nums) {
int result = 0;
for (int i = 0; i < 32; i++) {
int tempCount = 0;
for (int j = 0; j < nums.length; j++) {
int num = nums[j];
tempCount += (num >> i) & 1;
}
result += tempCount * (nums.length - tempCount);
}
return result;
}
}
合集:https://github.com/Cloudox/LeetCode-Record
版權所有:http://blog.csdn.net/cloudox_