![[LeetCode] Single Number II 位运算 [LeetCode] Single Number II 位运算](https://image.shishitao.com:8440/aHR0cHM6Ly9ia3FzaW1nLmlrYWZhbi5jb20vdXBsb2FkL2NoYXRncHQtcy5wbmc%2FIQ%3D%3D.png?!?w=700&webp=1)
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?
Hide Tags
数组中的数均出现3次,只有1个出现一次,可以参考http://www.cnblogs.com/Azhu/articles/3956568.html 说的。
[解题思路]
k为奇数时,如果k 大于10,就不用转换为2进制了,全部的数的同一位叠加(个位上的数叠加,十位上的叠加,百位上的....),mod k 之后结果放回对应位,便是目标int。
如果k <10,将数组中的数转换成2进制,全部数的同一位叠加,后mod k,得到的结果按位的位置还原成目标int。
#include <iostream>
using namespace std; class Solution {
public:
int singleNumber(int A[], int n) {
int cnt[]={};
int ret =;
for(int i=;i<n;i++){
int curnum = A[i];
while(curnum){
int idx= __builtin_ffs (curnum);
// cout<<idx<<endl;
cnt[idx]++;
curnum &=curnum-;
}
}
// for(int i=1;i<=32;i++)
// cout<<cnt[i]<<" ";
// cout<<endl;
int a=;
for(int i=;i<=;i++){
ret +=a*(cnt[i]%);
a=a<<;
}
return ret;
}
}; int main()
{
int a[]={,,,};
Solution sol;
cout<<sol.singleNumber(a,sizeof(a)/sizeof(int))<<endl;
return ;
}
discuss 中有一种使用内存更少的,
https://oj.leetcode.com/discuss/6632/challenge-me-thx
public int singleNumber(int[] A) {
int ones = , twos = ;
for(int i = ; i < A.length; i++){
ones = (ones ^ A[i]) & ~twos;
twos = (twos ^ A[i]) & ~ones;
}
return ones;
}
直观上难理解,只是思路是一样的,转换为二进制,然后每个位上面的数统计,然后mod(3),考虑1位,那么他的变化是
0 -> 1 ->2 -> 0
二进制就是:
00 -> 01 -> 10 -> 00
好了,这样只要两位就可以表示了,代码中的ones twos ,就这这个意思。