数组中数字出现的次数

一个整型数组 nums 里除两个数字之外,其他数字都出现了两次。请写程序找出这两个只出现一次的数字。要求时间复杂度是O(n),空间复杂度是O(1)。

class Solution {

    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] ints = solution.singleNumbers(new int[]{1, 2, 5, 2});
        System.out.println(Arrays.toString(ints));
    }

    public int[] singleNumbers(int[] nums) {
        int[] out = new int[2];
        int a = 0;
        int b = 0;
        int xorsum = 0;
        for (int num:nums){
            xorsum = xorsum^num;
        }
        int watershed = 1;
        while ((watershed&xorsum) == 0){
            watershed = watershed<<1;
        }
        for (int num:nums) {
            if ((num&watershed)==0){
                a = a^num;
            }else {
                b = b^num;
            }
        }
        out[0] = a;
        out[1] = b;
        return out;
    }
}

 题目来源:https://leetcode-cn.com/problems/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-lcof

原文地址:https://www.cnblogs.com/iuyy/p/13710629.html