The number 3 that appears only once

One: Title

Insert picture description here

Two: Solution

1) XOR

This question will use the XOR method. For the XOR operator and its use in C language, please refer to this article.

2) Detailed explanation

Step 1: Because the exclusive or the same is 0 and the difference is 1 , the question says that only two numbers in the entire array appear once, and all the other numbers appear twice. Therefore, all elements are XORed, and the XOR of the same element is 0, so the final XOR result must be the result of the operation of the two different elements. Assuming that the two different elements are X1 and X2, the result must be = X1^X2 .

Step 2: In this step, X1 and X2 should be separated. Here is an example

Insert picture description here

Insert picture description here

int* singleNumber(int* nums, int numsSize, int* returnSize)
{
    
    
    int ret=0;
    for(int i=0;i<numsSize;i++)
    {
    
    
        ret^=nums[i];
    }
    //第一步:因为异或是<b>相同为0,相异为1</b>,题目中说到,整个数组中只有两个数出现了一次,其余全部数均出现两次。所以把所有元素都进行异或操作,相同的元素异或为0,所以最终异或的结果一定是,那两个不同元素进行运算结果
    int m=0;
    while(m<32)
    {
    
    
        if(ret & (1<<m))
            break;
        else
            ++m;
    }
    //找出ret1的第m位为1

    int x1=0;
    int x2=0;
    for(int i=0;i<numsSize;i++)
    {
    
    
        if(nums[i] & (1<<m))
        {
    
    
            x1 ^= nums[i];
        }
        else
        {
    
    
            x2 ^= nums[i];
        }
    }   
    //找到第M位后,再次探查数组,如果某个数的第m位为,则为X1,反之则为X2
    int* retarr=(int*)malloc(sizeof(int)*2);
    retarr[0]=x1;
    retarr[1]=x2;
    *returnSize=2;
    return retarr;

}

Guess you like

Origin blog.csdn.net/qq_39183034/article/details/112758720