您的位置:首页 > 其它

[leetcode]Single Number II

2014-04-02 21:03 253 查看


Single Number II

My Submissions

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?

Have you been asked this question in an interview?

题目:除了一个元素以外其它元素出现3次,而只有一个元素出现一次

思路:将每个元素转化成二进制并将其对应的bit位置1,所以出过三次的元素对应的位应该是3的倍数,而最后只会剩下那只出现一次元素所对应的二进制位。

int singleNumber(int a[], int n) {
int bitCount[32] = {0};

for(int i = 0; i < n; i++){
int bit = 1;
for(int j = 0; j < 32; j++){
if(bit & a[i]){
bitCount[j] = (bitCount[j] + 1) % 3;
}
bit <<= 1;
}
}

int retNum = 0;

for(int i = 0; i < 32; i++){

retNum = retNum * 2 + bitCount[31 - i];
}

return retNum;
}


如果对其进一步可作扩展,除一个元素出现2次其它都出现3次,也可以用此方法。

如一个元素出现两次,一个出现1次,其它出现4次。也可以
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: