Thursday, June 12, 2014

LeetCode: 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:

We keep tree variables: one with the bits that appear $3k+1$ times, two with those that appear $3k+2$, and three with $3k$, such that $k$ is an integer.

public class Solution {
    public int singleNumber(int[] A) {
        int one = 0;
        int two = 0;
        int three = ~0;
        for(int i=0; i<A.length; i++)
        {
            int nextOne = (~A[i] & one) | (A[i] & three);
            int nextTwo = (~A[i] & two) | (A[i] & one);
            int nextThree = (~A[i] & three) | (A[i] & two);
            one = nextOne;
            two = nextTwo;
            three = nextThree;
        }
        return one;
    }
}

No comments :

Post a Comment