题目地址:
https://leetcode.com/problems/single-number-ii/description/
给定一个长 n n n数组 a a a,其中有且仅有一个数出现了 1 1 1次,别的数都出现了 3 3 3次,要求将出现了 1 1 1次的数求出来。
看成二进制数每一位单独处理。代码如下:
class Solution {
public:
int singleNumber(vector<int> &a) {
int res = 0;
for (int i = 0; i < 32; i++) {
int x = 0;
for (int c : a)
x += c >> i & 1;
if (x % 3)
res |= 1 << i;
}
return res;
}
};
时间复杂度 O ( n ) O(n) O(n),空间 O ( 1 ) O(1) O(1)。
2625

被折叠的 条评论
为什么被折叠?



