首页 > 其他 > 详细

LeetCode "477. Total Hamming Distance"

时间:2017-01-06 14:04:26      阅读:165      评论:0      收藏:0      [点我收藏+]

Fun one.. the punch line of this problem is quite common in Bit related problems on HackerRank - visualize it in your mind, and you will find: all bits on the same index among all numbers, will not involve other bits on other indices. So, we simply count number of 0s or 1s, on the same bit index from all numbers - we count it vertically..

class Solution {
public:
    int totalHammingDistance(vector<int>& nums) 
    {
        int n = nums.size();
        if(n < 2) return 0;
        
        // Pass 1: count num of 1s O(31n) -> O(n)
        vector<unsigned> cnt(31);
        for(auto v : nums)
        for(int i = 0; i < 31; i ++)
            cnt[i] += (v & (1 << i)) ? 1 : 0;
        
        // Pass 2: count
        int ttl = 0;
        for(int i = 0; i < 31; i ++)
            ttl += cnt[i] * (n - cnt[i]);

        return ttl;
    }
};

LeetCode "477. Total Hamming Distance"

原文:http://www.cnblogs.com/tonix/p/6255826.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!