Java implementation LeetCode 260 appear only once digital III (c)

260. appears only once in the digital III

Given an array of integers nums, of which there are exactly two elements appear only once, and the remaining elements all appear twice. Find out only once those two elements.

Example:

Input: [1,2,1,3,2,5]
Output: [3,5]
Note:

The results output order is not important, for the example above, [5, 3] is the correct answer.
Your algorithm should have linear time complexity. You can be implemented using only constant space complexity?

The PS:
1, the same number of two exclusive OR result is 0
2 0 XOR arbitrary number are an arbitrary number
3, bitwise exclusive or different compared to an identical or 0

class Solution {
     public int[] singleNumber(int[] nums) {
        int key = 0;
        for (int num : nums) {
            key ^= num;
        }
        
        //  保留位中最右边的1,且将其余为设为0
        //这两个数在1这个位置上不一样,一个是0一个是1
        key = key & (-key);
        int[] res = new int[2];
        for (int num : nums) {
            if ((num & key) == 0) {
                res[0] ^= num;
            } else {
                res[1] ^= num;
            }
        }
        return res;
    }
}
Released 1388 original articles · won praise 10000 + · views 1.41 million +

Guess you like

Origin blog.csdn.net/a1439775520/article/details/104643094
Recommended