- 136. 只出现一次的数字 简单
- 338. 比特位计数 简单
- 461. 汉明距离 简单

解法: 位运算

class Solution {
public:
int singleNumber(vector<int>& nums) {
int ret = 0;
for (auto e: nums) ret ^= e;
return ret;
}
};
- 时间复杂度:O(n),其中 n 是数组长度。只需要对数组遍历一次
- 空间复杂度:O(1)

解法1: Brian Kernighan 算法

class Solution {
public:
int countOnes(int x) {
int ones = 0;
while (x > 0) {
x &= (x - 1);
ones++;
}
return ones;
}
vector<int> countBits(int n) {
vector<int> bits(n + 1);
for (int i = 0; i <= n; i++) {
bits[i] = countOnes(i);
}
return bits;
}
};
- 时间复杂度:O(nlogn),需要对从 0 到 n 的每个整数使用计算「一比特数」,对于每个整数计算「一比特数」的时间都不会超过 O(logn)
- 空间复杂度:O(1), 除了返回的数组以外,空间复杂度为常数
解法2: 动态规划——最高有效位
class Solution {
public:
vector<int> countBits(int n) {
vector<int> bits(n + 1)
int highBit = 0
for (int i = 1
if ((i & (i - 1)) == 0) {
highBit = i
}
bits[i] = bits[i - highBit] + 1
}
return bits
}
}
- 时间复杂度:O(n)。对于每个整数,只需要 O(1) 的时间计算「一比特数」
- 空间复杂度:O(1), 除了返回的数组以外,空间复杂度为常数

解法1: 内置位计数功能
class Solution {
public:
int hammingDistance(int x, int y) {
return __builtin_popcount(x ^ y);
}
};
- 时间复杂度:O(1)。不同语言的实现方法不一,我们可以近似认为其时间复杂度为 O(1)
- 空间复杂度:O(1)
解法2: 移位实现位计数
- 记s=x⊕y, 不断检查S的最低位, 如果最低位为1, 令计数器加1, 不断右移s. 直到s变为0为止
class Solution {
public:
int hammingDistance(int x, int y) {
int s = x ^ y, ret = 0;
while (s) {
ret += s & 1;
s >>= 1;
}
return ret;
}
};
- 时间复杂度:O(logC)。其中 C 是元素的数据范围
- 空间复杂度:O(1)
解法3: Brian Kernighan 算法
class Solution {
public:
int hammingDistance(int x, int y) {
int s = x ^ y, ret = 0;
while (s) {
s &= s - 1;
ret++;
}
return ret;
}
};
- 时间复杂度:O(logC)。C是元素的数据范围
- 空间复杂度:O(1)