Leetcode 477. Total Hamming Distance
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given an integer array nums, return the sum of Hamming distances between all the pairs of the integers in the array.
Input: nums = [4, 14, 2]
Output: 6
Explanation: There are 3 pairs (4, 14), (4, 2), and (14, 2) with respective Hamming distances 2, 2, and 2; thus the sum is 6.
nums is in the range [1, 10^4].nums will be in the range [0, 10^9].nums contain duplicate numbers?
nums can contain duplicate numbers.nums be empty?
nums is 1 based on constraints.1 at this position and how many have 0.1 and a 0 at the same position between any two numbers contribute 1 to the Hamming distance).#include <vector>
using namespace std;
class Solution {
public:
int totalHammingDistance(vector<int>& nums) {
int total = 0, n = nums.size();
for (int i = 0; i < 32; i++) {
int countOnes = 0;
for (int num : nums) {
if (num & (1 << i)) {
countOnes++;
}
}
int countZeros = n - countOnes;
total += countOnes * countZeros;
}
return total;
}
};
total to 0 and get the size of nums.10^9 can be represented in 32 bits).i:
1 at bit position i (countOnes).0 at bit position i, so countZeros is n - countOnes.i is countOnes * countZeros.total.total.O(32 * n) = O(n), where n is the number of elements in the input array.
O(1), since we are using a constant amount of additional space regardless of the input size.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?