Lexi's Leetcode solutions

[leetcode] Single Number 2 | 一个数组除了x以外全都正好出现三次,求x

Posted on: October 7, 2013

bit好久没看真是全尼玛忘了。那些最基本的:

  • 显现a的第i位: a & 1 << i
  • 把a的第i位置零:a &= ~(1 << i)
  • 把result给populate回来:result |= 1 << i

创建一个长度为32的数组a,a[i]表示所有数字在i位出现的次数。假如a[i]是3的整数倍,则忽略;否则就把该位取出来组成答案。空间复杂度O(1).

public int singleNumber(int[] A) {
    int[] bv = new int[32];
    for (int i = 0; i < A.length; i++) {
        for (int j = 0; j < 32; j++) {
            bv[j] += (A[i] & (1 << j)) == 0 ? 0 : 1;
        }
    }
    int res = 0;
    for (int i = 0; i < 32; i++) {
        if (bv[i] % 3 != 0) {
            res |= 1 << i;
        }
    }
    return res;
}
Advertisements
Tags: , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: