-
- Title Description
- Link Address
- Solution
- Algorithmic interpretation
Title Description
Given 2*n + 2 numbers, every numbers occurs twice except, find them.
Example
Given [1,2,2,3,4,4,5,3] return 1 and 5
Challenge
O (n) time, O (1) extra space.
.
Link Address
http://www.lintcode.com/en/problem/single-number-iii/
Solution
vector<int>SINGLENUMBERIII ( vector<int>&a) {//Write your code here intRET =0; for(inti =0; I < a.size (); i++) {ret = ret ^ a[i]; }intLastoneval = ret-(Ret & (Ret-1)); vector<int>VEC1; vector<int>VEC2; for(inti =0; I < a.size (); i++) {if(A[i] & Lastoneval) {Vec1.push_back (a[i]); }Else{Vec2.push_back (a[i]); } }intRet1 =0;intRet2 =0; for(inti =0; I < vec1.size (); i++) {Ret1 = Ret1 ^ vec1[i]; } for(intj =0; J < Vec2.size (); J + +) {Ret2 = Ret2 ^ vec2[j]; } vector<int>Retvec; Retvec.push_back (RET1); Retvec.push_back (Ret2);returnRetvec; }
Algorithmic interpretation
In front of the problem solved 2*n+1, is now facing the problem of 2*n+2, we want to use what method can be divided into two sets of 2*n+2 to 2*n+1, and then in each set by the XOR operation, and finally can get two values.
How to convert to 2*n+1, as long as the solution to this, then all the problems solved.
Solve the key: All the numbers are different or, get the final result, and then find the last nonzero position. According to this location, all of this position is zero for a group, and all of this position is one for a group.
Find the last one is 1 position, using the algorithm:
C-(C-1) &c get the last non-zero position composed of the number
If C = 1100, the result is 0100.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Single number III