美文网首页Algorithm
找出数组中只出现一次的数

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

作者: 几千里也 | 来源:发表于2017-12-07 09:38 被阅读39次

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

    另一种解题思路还在研究

    相关文章

      网友评论

        本文标题:找出数组中只出现一次的数

        本文链接:https://www.haomeiwen.com/subject/mjarixtx.html