找出數(shù)組中只出現(xiàn)一次的數(shù)

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;
}

改的精致一點(diǎn)

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;
}

另一種解題思路還在研究

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容