Title: In an array of shapes except for two digits, the other numbers appear two times. Please write the program to find the two only occurrences of the number. The time complexity is O (n) and the space complexity is O (1).
Idea: The topic is very strict, O (n) time complexity, O (1) space complexity. The difficulty is not small. Refer to the book on the idea, the realization of the time, is mainly to make up for the lack of experience in bit computing.
Here is my code, implemented in C + +:
void findnumappareonce (const int data[], const int length, int * num1, int * num2) {if (data = NULL | | length < 2) retur N;int ident = 0;for (int i = 0; i < length; ++i) ident ^= data[i];const int bitposi = GETFIRSTBITIS1 (ident); *num1 = *num2 = 0;for (i = 0; i < length; ++i) {if (IsThisBit1 (Data[i], Bitposi)) *num1 ^= data[i];else*num2 ^= data[i];}}
The two functions involved in bit operations are as follows:
const int GETFIRSTBITIS1 (int ident) {int num = 0;while (((Ident >> num) & 0x1) = = 0) && (Num < (sizeof (int) * 8))//take care of the bit operators! (Of course with parentheses) + + Num;return num;} const BOOL ISTHISBIT1 (int data, const int POS) {return Data & (0x1 << POS);//there is a warning here.}
Test section:
#include <iostream.h>const int L = 10; int main () {const int Test[l] = {2, 3, 3, 2, 5, 5,, 8, 8};int A, B; Findnumappareonce (test, L, &a, &b) cout << a << "" << b << endl;return 0;}
The problem is very special and is hereby recorded. Temporarily do not promote, do not think more complex situation.
The sword refers to the offer--. Question 40: A number that appears only once in an array