题目

在一个数组 nums 中除一个数字只出现一次之外,其他数字都出现了三次。请找出那个只出现一次的数字。

示例 1:

输入:nums = [3,4,3,3]
输出:4

思路

int位存储

class Solution {
    public int singleNumber(int[] nums) {
        // 存储int 4*8=32每一位
        int[] arr = new int[32];
        for(int x : nums) 
            for(int i = 0; i < 32; i++) {
                arr[i] += x & 1;
                x >>= 1;// 从低到高
            }
        int res = 0, mod = 3;

        for(int i = 0; i < 32; i++) {
            res <<= 1;// 从高到低
            res += arr[31-i] % mod;
        }
        return res;
    }
}

编译 自动机状态转移

class Solution {
    public int singleNumber(int[] nums) {
        int one = 0, two = 0;
        // {one, two}每三个状态一次转移
        // {0, 0} {1, 0} {0, 1} {0, 0}
        for(int x : nums){
            one = (one ^ x) & ~two;
            two = (two ^ x) & ~one;
        }
        return one;
    }
}