您的位置:首页 > 其它

leetcode[137]:Single Number II

2015-07-25 14:27 267 查看
Single Number II

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?

int singleNumber(int* nums, int numsSize) {

int i,tmp;
int one = 0;//相应位出现次数模3余1的变量
int two = 0;//相应位出现次数模3余2的变量
for(i=0; i<numsSize; i++){

tmp = ((one ^ nums[i]) & (~two));
two = ((one & nums[i]) | (two & (~nums[i])));
one = tmp;
}
return one;
}


针对每一位来看,每一位出现的0或1 一定是3个3个相同的,多出来的那位组合在一起就是我们要找的数。进一步,无需考虑0的个数,题目保证了其他的都是3个,那么只需要统计1,有单个1剩余输出1,无单个1剩余输出0即可。

以下分析均只针对某一位:

假设nums[i]=0,即我们无需考虑的那位,会有:
tmp = ((one ^ 0) & (~two)) = one & ~two =one;(one 和 two 不可能同时为1)
two = ((one & 0) | (two & 1)) = two;
one = tmp =one;
即one = one; two = two;不考虑。

如果nums[i]=1,
tmp = ((one ^ 1) & (~two))
= ~one & ~two;(从未出现过,即one=two=0,此时tmp=1,否则tmp=0)
two = ((one & 1)| (two & 0))
= one;(又出现了1次,刚好出现两次的位应该和上一次的1次相同)
one = tmp =~one & ~two;


参考:

数据矿工:Single Number I & II
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  bit