Leetcode

  The key is to use two constant space(32 bits) to store how many times 1 or 0 showed up in the bit i. If times of 1 in bit i is not the multiple of 3, then the unique value's bit i is 1. Otherwise the unique value's bit i is 0. 

  Actually this algorithm can be extended to three times, four times, five times etc..


import java.util.*;


public class Solution {
    public int singleNumber(int[] A) {
        int[] zero = new int[32];
        int[] one = new int[32];
        
        for(int i=0;i<A.length;i++)
        {
        	for(int j=0;j<32;j++)
        	{
        		if( ((1<<j) & A[i]) != 0 )
        		{
        			one[j]++;
        		}
        		
        		else
        		{
        			zero[j]++;
        		}
        	}
        }
        
        int ans = 0;
        
        for(int k=0;k<32;k++)
        {
        	if(one[k] % 3 !=0 )
        	{
        		ans = (ans | (1<<k));
        	}
        }
        
        return ans;
    }
    
    public static void main(String[] args)
    {
    	int[] A = {-1,5,5,5};
    	
    	Solution sol = new Solution();
        System.out.println(sol.singleNumber(A));

    }
}


原文地址:https://www.cnblogs.com/zfyouxi/p/5124768.html