Find two occurrences of a number in an array

Source: Internet
Author: User

Title: In an integer array, except for two digits, the other numbers appear two times. Please write the program to find the two only occurrences of the number. The required time complexity is O (n), and the spatial complexity is O (1).

Or understanding is not deep enough.
The main idea of the problem is the pattern of numbers that appear once in an array, one-time traversal plus an XOR operation. Then this XOR value is definitely the difference or value of the two occurrences of the number. The result of 1 of the binary representation of this value indicates that the two numbers are different on that bit. So by doing this, we can separate the two occurrences of the number from the entire array with this bit.

By doing this, other two-time numbers will be divided into the same group, so the result is that there are two sets of data, each of which is an odd number of numbers, with only one occurrence.

#include <stdio.h>#include <assert.h>intFindouttwo (int*a,intNint&x,int&y) {assert (a); ASSERT (n>2);intresult=a[0]; for(intI=1; i<n;++i) Result^=a[i];intb=result&-result; x=0; y=0; for(intI=0; i<n;++i) {if(B&a[i]) x^=a[i];ElseY^=a[i]; }return 0;}intMain () {inta[]={1,1,2,2,3,3,4,4,5,6};intx, y; Findouttwo (A,sizeof(a)/sizeof(int), x, y);printf("%d%d\n", x, y); GetChar ();return 0;}

The result is:

Find two occurrences of a number in an array

Related Article

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.