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