Problem definition:There is a 2n + 1 number, with only one single vertex. Everything else is in pairs. Find the single vertex number. For example, 2 1 3 2 1. 3 is the answer.
Thought 1:Brute force search-compare each number with other numbers. If the same number is not found, the result is displayed. The time complexity is O (n2)
Thought 2:Sort search-first sort the sequence, and then find a pair from the front to the back until it is not paired. Time complexity, how can I get o (nlgn)
Thought 3:An exception or computing task. Time complexity O (N)
Let's look at Idea 3:
Principle:XOR operation (^) -- (BitFor example, 1 ^ 0 = 1, 1 ^ 1 = 0
In this way:
- The two identical numbers are equal to or equal to 0.
- Any number is different from zero or oneself (converted in place. 1 ^ 0 = 1, 0 ^ 0 = 0)
For example:5 ^ 5 = 0
5 ^ 0 = 5
For this question: 2 1 3 2 1, all are different or a bit: the same (2 ^ 2, 1 ^ 1) is 0, and the remaining 3 and 0 are different or their own 3.(Note:Exclusive or exclusiveExchange Law)
Reference code:
#include <stdio.h>int main(){ int a[5] = {2, 1, 3, 2, 1}; int aim = a[0]; for(i = 1; i < 5; i++) { aim = aim ^ a[i]; } printf("Result:", aim); return 0;}
The difference or is quite good in this regard. Another application:
There is no need for a third number to directly exchange two numbers:
#include <stdio.h>void swap(int *a, int *b){ *a = *a ^ *b; *b = *a ^ *b; *a = *a ^ *b;}int main(){ int a=3, b=5; swap(&a, &b); printf("%d\n%d", a, b); return 0;}
Of course, the same thinking can be used to complete this question:
#include <stdio.h>void swap(int *a, int *b){ *a = *a + *b; *b = *a - *b; *a = *a - *b;}int main(){ int a=3, b=5; swap(&a, &b); printf("%d\n%d", a, b); return 0;}