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:

public class Solution {
    public int singleNumber(int[] nums) {
        int count2=0, count1=0, mask=0;
        for(int n : nums){
            count2 ^= count1 & n;
            count1 ^= n;
            mask = ~(count2 & count1);
            count2 &= mask;
            count1 &= mask;
        }
        return count1;
    }
}
comments powered by Disqus