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
abare zeros,ris our number. From the above example,ais the left 0,bis the right 0 initially. For example,abare both zero, when we hit the 1 the first time, thenbis updated to 1,ais still 0, which is 01. When we hit the1the second time, thenabis 10. When we hit the1the third time, thenabreset to 00. We know that there is one number only appears once, so the result should stored inb. The formula for updating bothaandbwhen facing one number is below:1
2b = b xor r & ~a; a = a xor r & ~b;
Solution
1 | |