461. Hamming Distance and 477. Total Hamming Distance in Python

題目:app

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.函數

Given two integers x and y, calculate the Hamming distance.測試

Note:
0 ≤ xy < 231.this

Example:spa

Input: x = 1, y = 4
Output: 2
Explanation:
1   (0 0 0 1)
4   (0 1 0 0)
       ↑   ↑
The above arrows point to positions where the corresponding bits are different.

Example:code

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:blog

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

代碼:ip

這兩週比較慢,都沒有作題,趕忙作兩道。這兩個題目比較像,就放在一塊兒吧。漢明距離,就是把數字變成二進制,看有多少爲不同,不同的個數就是漢明距離。element

因此,第一題,僅僅比較兩個數字,我就用了常人都能想到的方法,轉換成二進制字符串,遍歷比較。惟一注意的就是將較短的字符串前面加0補足和長的相同位數。leetcode

   def hammingDistance(self, x, y):
        """
        :type x: int
        :type y: int
        :rtype: int
        """
        str1 = bin(x)[2:]
        str2 = bin(y)[2:]
        if len(str1) < len(str2):
            str1 = '0'*(abs(len(str2)-len(str1)))+str1
        else:
            str2 = '0' * (abs(len(str2) - len(str1))) + str2

        res = 0
        for i in range(0,len(str1)):
            if not str1[i:i+1] == str2[i:i+1]:
                res += 1
        return res

這個題經過了,但第二個題目要求給出一個字符串,兩兩求出漢明距離,而後相加。因而,我接着上題的函數,增長了一個遍歷,O(n^2):

 def totalHammingDistance(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not nums:
            return 0
        res = 0
        new_nums = sorted(nums)
        print sorted(set(nums))
        for i in range(len(new_nums)):
            for j in new_nums[i+1:]:
                print new_nums[i],j
                print self.hammingDistance(new_nums[i],j)
                res += self.hammingDistance(new_nums[i],j)
        return res

邏輯是沒錯,但不用想,leetcode中固然超時,會有一個包含1000個七、8位數字的列表去測試。唉,沒辦法,想不出來,百度了一下。這個漢明距離,其實能夠經過每一個bit位上面數字0的個數和1的個數相乘的結果,相加求得。等於逐一遍歷列表中每一個數字的每一個bit位,全部bit位遍歷一遍。

    def totalHammingDistance2(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not nums:
            return 0
        res = 0
        lists = []
        nums.sort()
        for i in nums:
            temp = list(bin(i)[2:])
            temp.reverse()
            lists.append(temp)

        for i in range(len(lists[-1])):
            count_0, count_1 = 0, 0
            for element in lists:
                # print element
                if len(element)-1 < i:
                    count_0 += 1
                elif element[i] == '0':
                    count_0 += 1
                elif element[i] == '1':
                    count_1 += 1
                # print count_0,count_1
            res += count_0 * count_1
        return res

試了下,果真沒問題!:)

相關文章
相關標籤/搜索