single-number
题目描述
Given an array of integers, every element appears three times except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
思想
一个数组里面除了一个数,其他数都出现了三次。希望你找出这个数
题目要求线性的时间内给出解决方案,普通的方法肯定不行的。
通过可以分析,如果一个数出现了三次,说明其相应bit位也出现了三次
比如3 (011) 出现了三次, 则说明bit1位的1出现了三次,bit2位的1出现了三次
我们可以建立一个32位的数字,来统计每一位上1出现的个数,我们知道如果某一位上为1的话,那么如果该整数出现了三次,对3去余为0,我们把每个数的对应位都加起来对3取余,
最终剩下来的那个数就是单独的数字。
代码
class Solution {
public:
int singleNumber(int A[], int n) {
int bits = 0;
int result = 0;
for(int i = 0; i < 32; i++) {
bits = 0;
for(int j = 0; j < n; j++){
bits += (A[j] >> i) & 1;
}
result |= ((bits % 3) & 1) << i;
}
return result;
}
};