lintcode-medium-Single Number II

Given 3*n + 1 numbers, every numbers occurs triple times except one, find it.

 

Example

Given [1,1,2,3,3,3,2,2,4,1] return 4

Challenge

One-pass, constant extra space.

 

public class Solution {
    /**
     * @param A : An integer array
     * @return : An integer 
     */
    public int singleNumberII(int[] A) {
        // write your code here
        
        if(A == null || A.length == 0)
            return 0;
        
        int[] count = new int[32];
        
        for(int i = 0; i < 32; i++){
            for(int j = 0; j < A.length; j++){
                count[i] += (A[j] >> i) & 1;
                count[i] %= 3;
            }
        }
        
        int res = 0;
        for(int i = 0; i < 32; i++)
            res = res | (count[i] << i);
        
        return res;
    }
}

 

posted @ 2016-04-06 03:36  哥布林工程师  阅读(107)  评论(0编辑  收藏  举报