LeetCode 排列組合 題目匯總
LeetCode 數字 題目匯總
LeetCode 動態規劃 題目分類匯總
干貨!LeetCode 題解匯總
題目描述
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.
題目分析
此題和第 461 題很像,初看是 461 題目的延伸。按照那道題的思路來做就是:
- 對數組中所有的數進行兩兩組合
- 對于每兩個數的組合,求一次 Hamming Distance
但是這樣做會超時,是因為兩兩組合的時間復雜度是 O(n^2),而求一次組合也需要最多 32 次循環。
那么應該怎么做這道題目呢?題目中的 Explanation 其實是一種誤導,我們真的有必要兩兩組合分別求 Hamming Distance 嗎?其實是沒有必要的,一次循環能否取得所有的 Hamming Distance?
通過分析得出,Hamming Distance 其實就是每一位的異同。那么這道題目就可以轉化為:求x個數每兩個數的組合中,每一位的異同數量。想到這里,就會發現其實x個數中每個數的數值并不重要,重要的是每一位有多少個0和多少個1。
假設有x個數中,第一位有m個0,n個1,則該位的Hamming Distance 是:m * n。
代碼
public int totalHammingDistance(int[] nums) {
if (nums == null || nums.length < 2) {
return 0;
}
int[] m = new int[31];// 存儲對應位數,有多少個0
for(int num : nums) {
for(int i = 0; i < 31; i++) {
if ((num & (1 << i)) == 0) {
m[i]++;
}
}
}
int result = 0;
for(int i = 0; i < 31; i++) {
result += m[i] * (nums.length - m[i]);
}
return result;
}