欢迎使用CSDN-markdown编辑器

Total HammingDistance –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.
  • 解题思路,当看到这个题时,最直接想到的就是求出每个数的二进制形式,然后在数组中两两比较每一位,这种思路虽然可以求得正确答案,但是最后提示超时,的确这种方法的时间复杂度近似为 O(n2logn) .贴出代码仅供参考。
 public int totalHammingDistance(int[] nums) {
        int result=0;
        for(int i=0;ilength;i++){
            for(int j=i+1;jlength;j++){
                int tmp=HammingDis(nums[i],nums[j]);
                result+=tmp;
            }
        }
        return result;
    }
    public String getBinary(int a){
        int tmp=a;
        StringBuilder sb=new StringBuilder();
        while(tmp!=0){
            sb.append(tmp%2);
            tmp=tmp>>1;
        }
        sb.reverse();
        return sb.toString();
    }
    public int HammingDis(int a,int b){
        String a_bit=getBinary(a);
        String b_bit=getBinary(b);
        int length=0;
        int len=Math.max(a_bit.length(),b_bit.length());
        if(len==b_bit.length()){//a_bit 始终存放长的字符串
            String tmp=b_bit;
            b_bit=a_bit;
            a_bit=tmp;
        }
        for(int i=len-1,j=b_bit.length()-1;i>=0||j>=0;i--,j--){
          if(j<0){
              if(a_bit.charAt(i)=='1'){
                    length++;
                }
                continue;
          }
            if(a_bit.charAt(i)!=b_bit.charAt(j)){
                length++;
            }
        }
        return length;
    }
  • 思路2 . 当看了别人的解答之后,才发现自己做的太过于直接,其实对于数组中所有数(个数为N)的某一位,例如第一位,假设1的个数为m ,0的个数为 Nm ,那么这就相当于一个排列组合问题,最终有 C1mC1Nm 个,所以问题就可以变成求数组中所有数的每一位中1的个数。
  public int totalHammingDistance(int[] nums){
        int len=nums.length;
        int total=0;
        for(int j=0;j<32;j++){
        int bitNum=0;
        for(int i=0;i>j)&1;
        }
        total+=bitNum*(len-bitNum);
        }
        return total;
    }

你可能感兴趣的:(数据结构与算法)