找出数组中只出现一次的数

Single Number

Given an array of integers, every element appears twice except for one. Find that single one.

public int singleNumber(int[] A) {
    int x = 0;
    for (int a : A) {
        x = x ^ a;
    }
    return x;
}

Single Number II

Given an array of integers, every element appears three times except for one, which appears exactly once. Find that single one.

逐位相加解题思路

To solve this problem using only constant space, you have to rethink how the numbers are being represented in computers -- using bits.
If you sum the ith bit of all numbers and mod 3, it must be either 0 or 1 due to the constraint of this problem where each number must appear either three times or once. This will be the ith bit of that "single number".
A straightforward implementation is to use an array of size 32 to keep track of the total count of ith bit.

初代粗糙版本

public int singleNumber(int[] A) {
    int[] bits = new int[32];
    for (int i = 0; i < 32; i++) {
        for (int j = 0; j < A.length; j++) {
            bits[i] += (A[j] >> i) & 1;
        }
    }
    int result = 0;
    for(int i=0; i<32; i++) {
        result += (bits[i] % 3) << i;
    }
    return result;
}

改的精致一点

public int singleNumber(int A[]) {
    if (A == null || A.length < 4) {
        return -1;
    }

    int bits[32] = {0};
    int result = 0;
    for (int i = 0; i < 32; i++) {
        for (int j = 0; j < A.length; j++) {
            if ((A[j] >> i) & 1) {
                bits[i]++;
            }
        }
        result |= ((bits[i] % 3) << i);
    }

    return result;
}

另一种解题思路还在研究

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。