Algorithm: only numbers appear in the array once.
Question
In an integer array, all the numbers except two appear twice. Write a program to find the numbers that appear only once. The time complexity is O (n) and the space complexity is O (1 ).
Question
Tip1: if only one number appears in array A and the other number appears twice, it is very easy to find the number, the value is A [0] ^ A [1] ^... ^ A [n-1]
Therefore, you need to find a way to convert the problem to the problem scenario in tip1.
Tip2: returns the XOR of each number in the array in the question. The obtained value is x. In fact, x is the exclusive or value of the two numbers in the array that appear only once.
If the k of x is 1, all the numbers in the original array are divided into two arrays according to whether the k is 1.
Then we can implement the tip1 solution for the two arrays. Because each sub-array contains a number that only appears once, and the remaining number appears twice.
Code
#include
#include
#include
#include
#include
#include
using namespace std;class Solution {public: // A is an array, whose length is n void solve(int A[], int n) { int x = 0; for (int i = 0; i < n; i++) x ^= A[i]; // assert x != 0 int lowestBit = x - (x & (x-1)); int left = 0, right = n-1; while (left <= right) { while (left <= right && (A[left]&lowestBit) == 0) left++; while (left <= right && (A[right]&lowestBit) == 1) right--; if (left <= right) swap(A, left, right); } int x1 = 0, x2 = 0; for (int i = 0; i < left; i++) x1 ^= A[i]; for (int i = left; i < n; i++) x2 ^= A[i]; printf("x1:%d, x2:%d\n", x1, x2); } void swap(int A[], int i, int j) { int tmp = A[i]; A[i] = A[j]; A[j] = tmp; }}; int main() { int A[] = {2, 3, 2, 4, 3, 5, 6, 7, 7, 6}; Solution solution; solution.solve(A, sizeof(A)/sizeof(int)); return 0;}