2014年1月14日星期二

LeetCoder - 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?

public class Solution {
    public int singleNumber(int[] A) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        int count[] = new int[32];
        int result = 0;
        for (int i = 0;i < 32;++i) {
            count[i] = 0;
            for (int j = 0;j < A.length;++j) {
                if (((A[j] >> i) & 1) == 1) {
                    count[i] = (count[i] + 1) % 3;
                }
            }
            result |= (count[i] << i);
        }
        return result;
    }
}

没有评论:

发表评论