Interview Questions---find Two occurrences of the number in the array

Source: Internet
Author: User

Title Description: to an array, there are two numbers appear only once, the other number appears two times, please find out these two numbers;

Example: Input 2 4 2 7 4 9

Output 7 9

Idea: Suppose to find out the two numbers for x, y put all the number of different or, the result is x and y xor value, then certainly not 0, then the value of the binary at least one is 1, that is, x and y binary on this one must be a 0, a 1, then you can divide the array into two arrays according to this bit, X and y are in different arrays, and the next value that is directly different or out of each array is the result;

The code is as Follows:

#include <iostream>#include<cstdio>using namespacestd;intnum1,num2;intSinglenumber (intnums[],intLength) {num1=num2=0; if(length<2)return-1; intRe=0;  for(intI=0; i<length;i++) Re^=nums[i]; intInd=0;  while((re&1)==0&& (ind<8*sizeof(int)) {re=re>>1; ++ind; }     for(intj=0; j<length;++J) {intt= (nums[j]>>ind) &1; if(t) num1^=nums[j]; Elsenum2^=nums[j]; }}intmain () {intnums[ -]={2,4,2,7,4,9}; Singlenumber (nums,6); cout<<num1<<" "<<num2<<endl; return 0;}

Interview Questions---find Two occurrences of the number in the array

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.