Leetcode-477. Total Hamming Distance

来源:互联网 发布:画巻展开效果 js 编辑:程序博客网 时间:2024/05/02 02:57

前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。

博客链接:mcf171的博客

——————————————————————————————

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, 2Output: 6Explanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (justshowing 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 to 10^9
  2. Length of the array will not exceed 10^4.
这个题目实质上就是找每一位有1的个数数多少,然后0的个数就是数组长度减去1个个数,每一位的组合数就是count_1 * count_0.

解法1:每次都同时计算所有数字的同一位,时间复杂度O(10^4 *  10^9 ),空间复杂度O(10 ^ 4)Your runtime beats 1.26% of java submissions.

public class Solution {    public int totalHammingDistance(int[] nums) {        int count = 0;List<Integer> data = new ArrayList<Integer>();for(int item : nums) data.add(item);while(data.size()!=0){count +=  diff(data,nums.length);}return count;    }    public int diff(List<Integer> nums, int totalNum){int count = 0;int count_1 = 0, count_0 = 0;for(int i = 0; i < nums.size(); ){int val = nums.get(i);if(val % 2 == 1) count_1 ++;val /= 2;if(val == 0)nums.remove(i);else{nums.set(i,val); i ++;}}count_0 = totalNum - count_1;count = count_1 * count_0;return count;    }}
解法2:用一个31位的数组来保存每一位1的数字,时间复杂度O(10^4 *  10^9 ),空间复杂度O(1)Your runtime beats 5.03% of java submissions.

public class Solution {    public int totalHammingDistance(int[] nums) {        int[] flags = new int[31];        for(int item : nums){            int index = 0;            while(item != 0){                if(item %2 != 0) flags[index] ++;                index ++;                item = item /2;            }        }        int count = 0;        for(int item : flags){            count += item * (nums.length - item);        }        return count;    }}





0 0
原创粉丝点击