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?
原题地址
class Solution {
public:
int singleNumber(int A[], int n) {
if(A==NULL || n<=0) return 0;
sort(A, A+n);
int count = 1;
int ret = A[0];
for(int i=1; i<n; ++i){
if(A[i] == A[i-1])
++count;
else{
if(count == 1){
break;
}
else if(count == 3){
count = 1;
}
}
ret = A[i];
}
return ret;
}
};class Solution {
public:
int singleNumber(int A[], int n) {
if(A==NULL || n<=0) return 0;
int count = 0;
int ret = 0;
for(int i=0; i<32; ++i){
count = 0;
int d = 1<<i;
for(int j=0; j<n; ++j){
if( A[j] & d )
++count;
}
if(count % 3 != 0)
ret = ret | d;
}
return ret;
}
};
[ LeetCode ] Single Number II,布布扣,bubuko.com
原文:http://blog.csdn.net/swagle/article/details/28394529