Tuesday, February 11, 2014

Single Number II

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?

Solution:
An int has 32 bits, iterate all bits of sum. If it is a multiplication of 3, then dismiss; otherwise, mod 3 to get result at that bit. Very elegant!

public class Solution {
    public int singleNumber(int[] A) {
        int result = 0;
        int temp;
        for(int i = 0; i < 32; i++){
            temp = 0;
            for(int j = 0; j < A.length; j++){
                if(((A[j] >> i) & 1) == 1){
                    temp++;
                }
            }
            temp = temp % 3;
            result = result | (temp << i);
        }
        return result;
    }
}

No comments:

Post a Comment