码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode - Single Number II

时间:2014-10-09 15:29:08      阅读:243      评论:0      收藏:0      [点我收藏+]

标签:style   io   ar   java   for   sp   on   amp   new   

  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));

    }
}


Leetcode - Single Number II

标签:style   io   ar   java   for   sp   on   amp   new   

原文地址:http://blog.csdn.net/tspatial_thunder/article/details/39928031

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!