时间复杂度 O(32n)=O(n),空间复杂度O(1)
#include <map> #include <set> #include <queue> #include <stack> #include <math.h> #include <time.h> #include <stdio.h> #include <stdlib.h> #include <iostream> #include <limits.h> #include <string.h> #include <string> #include <algorithm> #include <sstream> #include <iomanip> #define Min(a,b) (((a) < (b)) ? (a) : (b)) #define Max(a,b) (((a) > (b)) ? (a) : (b)) #define read freopen("in.txt","r",stdin) #define write freopen("out.txt","w",stdout) using namespace std; //#define MAXBITNUM 32 //#define MAXNUM 100000 //int bitnumvec[MAXNUM][MAXBITNUM]; int singleNumber(int A[], int n) { //vector<int*> vec; if(n==1) return A[0]; const int MAXBITNUM=32; //int bitnumvec[MAXNUM][MAXBITNUM]; int** bitnumvec=new int*[n]; for(int i=0;i<n;i++) bitnumvec[i]=new int[MAXBITNUM](); for(int i=0;i<n;i++) { int offset=MAXBITNUM-1; if(A[i]==-pow(2.0,31))//-2^31 { bitnumvec[i][0]=1;//, 10000000...000 } else//others { if(A[i]<0&&A[i]>-pow(2.0,31))//negative { bitnumvec[i][0]=1;//1 means negative, 0 means positve A[i]=-A[i]; } while(A[i]!=0) { bitnumvec[i][offset]=A[i]%2; //bitnum[offset]=A[i]%2; A[i]=A[i]/2; offset--; } } //reverse(vec.begin(),vec.end()); //vec.push_back(bitnum); } //memset(bitnum,0,sizeof(int)*MAXBITNUM); int bitnum[MAXBITNUM]; memset(bitnum,0,sizeof(int)*MAXBITNUM); int x=0; for(int i=0;i<MAXBITNUM;i++) { //if(i==MAXBITNUM-1) // int y=1; for(int j=0;j<n;j++) { //if(bitnumvec[j][0]==0) bitnum[i]+=bitnumvec[j][i]; //else if(bitnumvec[j][0]==1) // bitnum[i]-=bitnumvec[j][i]; } bitnum[i]=bitnum[i]%3; if(i>0) x+=bitnum[i]*pow(2.0,MAXBITNUM-1-i); } if(bitnum[0]==1 &&x !=0) x=-x; else if(bitnum[0]==1 && x==0) x=-pow(2.0,31); //for(int i=0;i<MAXBITNUM;i++) //int x; //for(int i=0;i<MAXBITNUM;i++) for(int i=0;i<n;i++) delete[] bitnumvec[i]; delete[] bitnumvec; return x; } int main() { //int x=-3%2; int a[]={-2,-2,-2147483648,-2}; cout<<singleNumber(a,4)<<endl; return 0; }
找唯一不出现三次而出现1次的数子O(n)位运算算法,布布扣,bubuko.com
原文地址:http://blog.csdn.net/richardzrc/article/details/37369351