Write catalog title here
topic
Except for two numbers in an integer array nums, other numbers appear twice. Please write a program to find these two numbers that only appear once. The required time complexity is O(n), and the space complexity is O(1).
Simplified version
First, let's study the simplification problem: only one number in an array appears once, and all other numbers appear twice.
method one:
Judge by sorting and two pointers.
This method has high time complexity and space complexity.
void bubbleSort(int arr[], int size) {
//顺序
for (int a = 0; a < size - 1; a++){
//最多size-1轮比较
for (int b = 0; b < size - 1 - a; b++){
if (arr[b]>arr[b + 1]){
int c = arr[b];
arr[b] = arr[b + 1];
arr[b + 1] = c;
}
}
}
}
int findlone(int* arr1,int size){
assert(arr1);
bubbleSort(arr1, size);
int *one = arr1;
int* two = arr1 + 1;
while (two){
if (*one == *two){
one += 2;
two += 2;
}
else{
return *one;
}
}
return 0;
}
Method two (optimal):
XOR
int findlonely(int *arr, int size){
int a = 0;
for (int i = 0; i < size; ++i){
a = a^arr[i];
}
return a;
}
Method three:
Counting method
int find3(int* arr, int size){
int num = 0;
for (int i = 0; i < size; i++){
num = 0;
for (int j = 0; j < size; j++){
if (arr[i] == arr[j]){
num++;
}
}
if (num == 1){
return arr[i];
}
}
return ;
}
Complete solution
Ideas:
1. Solve the exclusive OR of all elements;
2. Find the 1 in the lowest position of the binary solution (just find a 1 to separate the two numbers);
3. Solve the exclusive OR in the displacement operation.
int sumeor(int *arr, int size){
int a = 0;
for (int i = 0; i < size; ++i){
a = a^arr[i];
}
return a;
}
int finddifferentX(int num){
int count = 0;
while (count < 32 && (num & 1) == 0){
num = num >> 1;
count++;
}
return count;
}
void findtwosingle(int *arr, int size){
if (size < 2){
return;
}
int count = 0;
count = finddifferentX(sumeor(arr, size));
int num1 = 0;
int num2 = 0;
for (int i = 0; i < size; i++){
//arr[i] = arr[i] >> count;
if (((arr[i] >> count)&1) == 0){
num1 = num1^arr[i];
}
else{
num2 = num2^arr[i];
}
}
printf("%d %d", num1, num2);
}