Good use of the different or can produce magical effects.
The nature of an XOR operation:
any one number XOR or it is equal to 0 . That is, if we vary from start to finish or every number in the array, the final result is exactly the one that appears only once, because those numbers that appear two times are all offset by XOR.
Examples:
The given size is an array of N, the elements in the array are not duplicated, the element size range is 1~ (n+1), the goal is to find the number of the first miss. The time complexity of O (N) is required, and the space is O (1).
Because this array has only N elements in total, there must be a number in the 1--n+1 that does not exist. Set res = 0, using XOR or operation, first let res and subscript +1 xor, then with each number of different or. The number that appears two times is exactly the same or 0. The rest is the result.
<span style= "FONT-SIZE:14PX;" >//You can also with includes, for example://#include <algorithm>int solution (vector<int> &a) { // Write your code in c++98 int res = 0; int max = A.size (); if (max==0) { return 1; } for (int i=0;i<a.size (); i++) { res^= (i+1); if (A[i]<=max) { res^=a[i]; } } return res==0?max+1:res;} </span>
A similar other question:
title: In an integer array, except for two digits, the other numbers appear two times. Please write the program to find the two only occurrences of the number. The required time complexity is o (n), and the spatial complexity is O (1).
See the answer: http://zhedahht.blog.163.com/blog/static/2541117420071128950682/
Reference documents:
Http://www.cnblogs.com/parapax/p/3632255.html
XOR operation in C + + ^