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:
- Elements of the given array are in the range of
0
to10^9
- Length of the array will not exceed
10^4
.
解法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
- LeetCode 477. Total Hamming Distance
- 【Leetcode】477. Total Hamming Distance
- LeetCode 477. Total Hamming Distance
- [leetcode] 477. Total Hamming Distance
- LeetCode 477. Total Hamming Distance
- LeetCode 477. Total Hamming Distance
- LeetCode 477. Total Hamming Distance
- Leetcode-477. Total Hamming Distance
- 【LeetCode】 477. Total Hamming Distance
- [leetcode]477. Total Hamming Distance
- LeetCode 477. Total Hamming Distance
- [LeetCode]477. Total Hamming Distance
- LeetCode 477. Total Hamming Distance
- Leetcode: 477. Total Hamming Distance
- leetcode 477. Total Hamming Distance
- leetcode 477. Total Hamming Distance
- LeetCode 477. Total Hamming Distance
- leetcode 477. Total Hamming Distance
- HTML基础:文本的排版格式(5)
- Nunit 写法不错
- MVC之构建一个购物网站
- IOS开发入门(8)-本地化(1)
- PHPStorm设置xdebug工具调试php(使用浏览器或不使用浏览器两种方法)
- Leetcode-477. Total Hamming Distance
- 读取配置文件时候获取资源位置
- hdu 6000 Wash
- 元旦快乐~
- Android下使用chcon修改文件的安全上下文(file_contexts)
- tensorflow的cross_entropy(loss)=nan问题
- 如何在同一主机切换python2与python3的使用
- 深度学习的一些教程
- 453. Minimum Moves to Equal Array Elements