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?public class Solution {
public int singleNumber(int[] A) {
int N=64;
int countbit[]=new int[N];
int countbitN[]=new int[N];
int res=0;
int resN=0;
for(int i=0;i<A.length;i++)
{
int n=A[i];
if(n>=0)
for(int j=0;j<N;j++)
countbit[j]+=((n&(1<<j))>0)?1:0;
else
for(int j=0;j<N;j++)
countbitN[j]+=((-(1+n)&(1<<j))>0)?1:0;
}
for(int j=0;j<64;j++)
{
if(countbit[j]%3>0)res|=(1<<j);
if(countbitN[j]%3>0)resN|=(1<<j);
}
return (resN>0)?-(resN+1):res;
}
}
No comments:
Post a Comment