Once arrays of numbers appeared only (30)

topic

[In addition to an array of integers in two numbers, the other numbers appear twice. Please write a program to find these two figures appear only. ]


Method 1: The container in the STL multiset

1, the analysis
because only two of the array numbers appear only once, other figures appear twice, multiset in the count can be used to find () function.
2, the code

class Solution {
public:
    void FindNumsAppearOnce(vector<int> data,int* num1,int *num2) {
        multiset<int> mp;
        for(auto &i:data)
        {
            mp.insert(i);
        }
        bool flag=true;
        for(multiset<int>::iterator it=mp.begin();it!=mp.end();it++)
        {
            if(mp.count(*it)==1 && flag)
            {
                *num1=*it;
                it++;
                flag=false;
            }
            if(mp.count(*it)==1)
            {
                *num2=*it;
                break;
            }
        }
    }
};

Method Two:

1, the analysis
because only two of the array numbers appear once, other figures have emerged twice, so the array XOR operation, the result must be one of these two numbers appear only XOR result. Because the other numbers appeared twice, the same number XOR result is 0. Thus the array may be divided into two sub-arrays, each sub-array is only one of a number appears, all the other figures appears twice. Results of this sub-arrays of two XOR operation is the only number that appears once a.
The digital is divided into two sub-arrays, each sub-array and one containing only a number appears, the results need to find the location of the array of the first exclusive OR 1, then the number of the position of each number are compared, the digits are in a group, the digit 0 is set in a. So that it can be reasonable to separate it.
2, the code

class Solution {
public:
    void FindNumsAppearOnce(vector<int> data,int* num1,int *num2) {
        if(data.size()<2)
            return ;
        int exor=0;
        //第一次将数组进行异或操作,来得到两个只出现一次的数的异或结果
        for(vector<int>::iterator it=data.begin();it!=data.end();++it)
        {
            exor^=*it;
        }
        unsigned int firstIndex=GetFirstIndex(exor);
        *num1=0,*num2=0;
        for(int i=0;i<data.size();++i)
        {
            if(IsBitOne(data[i],firstIndex))
                *num1^=data[i];
            else
                *num2^=data[i];
        }
    }
    //求第一次出现1的位置
    unsigned int GetFirstIndex(int num)
    {
        unsigned int index=0;
        while(((num & 1)==0) && (index<8*sizeof(int)))
        {
            num=num>>1;
            ++index;
        }
        return index;
    }
    //分组的判读依据
    bool IsBitOne(int k, unsigned int index)
    {
        k=k>>index;
        return (k & 1)==1;
    }
};
Published 215 original articles · won praise 49 · views 110 000 +

Guess you like

Origin blog.csdn.net/Jeffxu_lib/article/details/104895508