Saturday, July 4, 2015

Single Number II

Given 3*n + 1 numbers, every numbers occurs triple times except one, find it.
Have you met this question in a real interview? 
Yes
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
        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);
            }
        }
        int res = 0;
        for(int i = 0; i < 32; i++){
            res += (count[i] % 3) << i;
        }
        return res;
    }
}

1 comment:

  1. Here is another solution
    public class Solution {
    public int singleNumber(int[] nums) {
    int p = 0;
    int q = 0;
    for(int i = 0; i<nums.length; i++){
    p = q & (p ^ nums[i]);
    q = p | (q ^ nums[i]);
    }
    return q;
    }
    }
    Analysis from this blog post : http://traceformula.blogspot.com/2015/08/single-number-ii-how-to-come-up-with.html 

    ReplyDelete