Problem
Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Example 1:
1 |
|
Example 2:
1 |
|
Explanation
-
We need to think of some method to make some binary numbers reset to zero after three changes. We can use two binary number
00
, when facing three times of the same number, it should reset back to00
,00->01->10->00
.1
2
300 (+) 1 = 01 01 (+) 1 = 10 10 (+) 1 = 00 ( mod 3)
-
Init
a
b
are zeros,r
is our number. From the above example,a
is the left 0,b
is the right 0 initially. For example,a
b
are both zero, when we hit the 1 the first time, thenb
is updated to 1,a
is still 0, which is 01. When we hit the1
the second time, thenab
is 10. When we hit the1
the third time, thenab
reset to 00. We know that there is one number only appears once, so the result should stored inb
. The formula for updating botha
andb
when facing one number is below:1
2b = b xor r & ~a; a = a xor r & ~b;
Solution
1 |
|