40. Numbers that appear only once in an array

Topic description

         All but two numbers in an integer array appear twice. Please write a program to find these two numbers that appear only once;

Problem solving ideas

         Two unequal elements must have a difference in bit-level representation;

         The result obtained by XORing all elements of the array is the result of XORing two elements without duplicates;

        diff &= -diff to get the bit whose rightmost side of diff is not 0, that is, the bit that is different on the rightmost side of the bit-level representation of two elements that do not have duplicates. Using this bit, the two elements can be converted differentiate;

//num1, num2 are arrays of length 1 respectively. Outgoing parameters
//Set num1[0], num2[0] as the return result
public class Solution {
    public void FindNumsAppearOnce(int[] nums, int num1[], int num2[]) {
        int diff = 0;
        for (int num : nums)
            diff ^= num;
        // get the rightmost bit
        diff &= -diff;
        for (int num : nums) {
            if ((num & diff) == 0)
                num1[0] ^= num;
            else
                num2[0] ^= num;
        }
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325868266&siteId=291194637