2014年11月28日星期五

[Leetcode] Single Number I & II

Given an array of integers, every element appears twice 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 int singleNumber(int[] A) {
        int res = 0;
        for(int i = 0; i < A.length; i++)
            res = res ^ A[i];
        return res;
    }

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 int singleNumber(int[] A) {
        int[] bits = new int[32];
        for(int i = 0; i < A.length; i++) {
            for(int j = 0; j < 32; j++) {
                if((A[i] & (1 << j)) != 0)
                    bits[j]++;
            }
        }
        int res = 0;
        for(int i = 0 ; i < 32; i++) {
            bits[i] = bits[i] % 3;
            if(bits[i] != 0)
                res = res + (1 << i);
        }
        return res;
    }

没有评论:

发表评论