260 Single Number III
Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.
For example:
Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].
Note: The order of the result is not important. So in the above example, [5, 3] is also correct. Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
//O(N^2) time (SLOW!!!)
//O(NlogN) + O(N) [faster, but still not fast enough]
//O(N), O(1) space
Here I know that if I first xor all the elements, the return will be the two unique xor'd elements.
x ^ y = (2 unique elements xor'd)
.If I can find one of the unique elements, I can find the other, since
(2 unique elements xor'd) ^ x = y
, as the inverse of xor = xor.So we've reduced the problem into just finding any one of the first single numbers.
Doing this isnt really intuitive, we apparently have the first find the first set bit of cum that ill call temp. Then we xor anything in the number of sequence again that is >= temp, inverse of temp, or is zero. This alone will return the first unique element.
Last updated
Was this helpful?