Sword Finger Offer Interview Question 56: The number of times the number appears in the array (bit operation, review)

For this question, there is no idea, just look at the idea of ​​the answer directly, the idea of ​​the answer is

Because the XOR of two identical numbers is 0, the XOR of all numbers is the XOR of two different numbers. Among them, the first bit of the XOR value is 1, which represents this The two numbers are firstly different in this one,

Therefore, according to whether this bit is 1 or 0, divide the array, divide the two arrays, only one number appears once in the two arrays, and perform the exclusive OR operation on all the numbers to find two Number.

 

Knowledge points:

Bitwise and, bit shift left

int div = 1;
while((div&res)==0){
    div<<=1;
}

XOR

a^b

Bitwise AND, 1 is shifted to the left, you can judge whether it is 0, but you cannot judge whether it is 1, because at the same time, 1 is not necessarily in the lowest bit.

 

Answer code

    public int[] singleNumbers(int[] nums) {
        int res = 0;
        for(int count = 0;count<nums.length;count++){
            res ^= nums[count];
        }
        int div = 1;
        while((div& res) == 0){
            div<<=1;
        }
        int a = 0;
        int b = 0;
        for(int count = 0;count<nums.length;count++){
            if((nums[count]&div) == 0){
                a ^= nums[count];
            }else{
                b ^= nums[count];
            }
        }
        return new int[]{a,b};
    }

 

Guess you like

Origin blog.csdn.net/qq_40473204/article/details/115009038