The sword refers to the offer surface question 40-two occurrences of a number in an array

Source: Internet
Author: User

Tag: Sword refers to two occurrences of a number in an offer array

Topic:

In an array of integers, except for two digits, the other numbers appear two times. Please write the program to find the two only occurrences of the number. Requires time complexity O (n), Spatial complexity O (1).


Basic idea:

http://blog.csdn.net/wtyvhreal/article/details/44260321

#include <iostream>using namespace Std;int Find1 (int n)//start looking for the first 1 position {int Index=0;while (n&1) ==0 & & (index<8*sizeof (int))) {N=n>>1;++index;} return index;} BOOL Isbit1 (int n,int index) {n=n>>index;return (n&1);} void foo (int data[],int len) {if (len<2) return;int result=0;for (int i=0;i<len;i++) Result^=data[i];int index = Find1 (result), int x=0;int y=0;for (int j=0;j<len;j++) {if (Isbit1 (Data[j],index)) x^=data[j];elsey^=data[j];} cout<<x<< "" <<y<<endl;} void Main () {int a[8]={2,4,3,6,3,2,5,5};foo (a,8);}


The sword refers to the offer surface question 40-two occurrences of a number in an 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.