Home LeetCode-477 Total Hamming Distance
Post
Cancel

LeetCode-477 Total Hamming Distance

Description

给定数组\(a[]\),求数组内任意元素对的汉明距离之和

Constraints

  • \(1 \le a.length \le 10^4\)
  • \(0 \le a_i \le 10^9\)
  • 返回值必然在整型int范围内

Solution

按位处理贡献,每一位统计0和1的贡献

Code

class Solution {
public:
    int totalHammingDistance(vector<int>& nums) {
        if(nums.size() <= 0) return 0;
        int res = 0;
        for(int i = 0; i < 32; i++) {
            int setCount = 0;
            for(int j = 0; j < nums.size(); j++) {
                if(nums[j] & (1 << i)) setCount++;
            }
            res += setCount * (nums.size() - setCount);
        }
        return res;
    }
};

LeetCode-477 Total Hamming Distance

This post is licensed under CC BY 4.0 by the author.
Contents