Problem:
Given 2*n + 2 numbers, every numbers occurs twice except two, find them.
Have you met this question in a real interview? Yes
Example
Given [1,2,2,3,4,4,5,3] return 1 and 5
Note:
- The order of the result is not important. So in the above example, [5, 1] is also correct.
- Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
Challenge
O(n) time, O(1) extra space.
Solution:
This problem is also about bit operation.
First we xor all the numbers in the array.
Then we can get the last digits which equals 1.
The bit represent the last different bit of the two exceptional numbers.
Next, we use the bit to separate the numbers in the array into two group, and use xor to link the numbers in each group.
After the iteration stop, each number left in each group should be the two results.
1 | /************************************************************************* |