剑指Offer面试题56:数组中数字出现的次数(位运算,要复习)

这道题,没思路,直接看的答案的思路,答案的思路是

因为两个相同的数字,异或得0,因此,对所有的数进行异或,得到的就是两个不同的数的异或,其中,异或值第一个为1的位,代表了这两个数字,首先在这一位不相同,

因此,按照这一位为1还是0,对数组进行划分,对划分得到的两个数组,这两个数组,只有一个数出现了一次,分别对所有的数进行异或运算,就能找到两个数。

知识点:

按位与,位左移

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

异或

a^b

按位与,1左移,可以判断是否为0,但是不能判断是否为1,因为相同的时候,1不一定在最低位。

答案代码

    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};
    }

猜你喜欢

转载自blog.csdn.net/qq_40473204/article/details/115009038