2014年4月27日 星期日

[LeetCode] Single Number II

Problem:
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:O(n)
public class Solution {
    public int singleNumber(int[] A) {
        int value = 0;
        for(int i =0; i<32;i++){
            value|= (getBit(A,i)<<i);
        }
        return value;
    }
    
    public int getBit(int[] A, int digit){
        int sum = 0;
        for(int i =0; i<A.length;i++){
            sum+=( (A[i]>>digit) &1);
        }
        return sum%3;
    }
}
Key Concept: count each bit count mod 3 to get the extra number

沒有留言:

張貼留言