LeetCode筆記:477. Total Hamming Distance

問題:

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:

  1. Elements of the given array are in the range of 0 to 10^9
  2. Length of the array will not exceed 10^4.

大意:

兩個(gè)整數(shù)之間的Hamming distance是指它們?cè)诙M(jìn)制表示上各個(gè)位的數(shù)不同的個(gè)數(shù)。
現(xiàn)在你的工作是找出每對(duì)數(shù)字之間的Hamming distance的總和。

例子:

輸入:4, 14, 2

輸出:6

解釋:在二進(jìn)制表示法中,4是 0100,14是 1110,2是 0010(這里只顯示四位)。所以答案應(yīng)該是 HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6。

注意:

  1. 給出的元素范圍在0到10的9次方。
  2. 數(shù)組的長(zhǎng)度不會(huì)超過10的4次方。

思路:

這里如果使用雙重循環(huán)一個(gè)個(gè)比較兩個(gè)數(shù)字的差異,可以算出來,但是在時(shí)間上會(huì)有用例超時(shí)。

這里換一種思路,我們看每個(gè)數(shù)都有32位,對(duì)每一位,我們統(tǒng)計(jì)數(shù)組中的數(shù)再這一位上為1的有幾個(gè)數(shù),那么在這一位上,所有兩對(duì)數(shù)不同的情況是為1的數(shù)量乘以為0的數(shù)量,是個(gè)排列組合的問題。對(duì)每一位我們都這樣操作,就可以很快得出結(jié)果了。

代碼(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
版權(quán)所有:http://blog.csdn.net/cloudox_

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容