Problem
Given a non-empty array of integers, every element appears twice except for one. 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 can use
XOR
to solve this problem. We know that0 XOR 0 = 0
,1 XOR 1 = 0
,0 XOR 1 = 1 XOR 0 = 1
. For example, we can initialize the res is0000
first, loop through all the numbers, if the first number is1010
thenres XOR num = 0000 XOR 1010 = 1010
. If the second number is also1010
, thenres = res XOR num = 1010 XOR 1010 = 0000
; If the third number is1100
, then theres = res XOR num = 0000 XOR 1100 = 1100
. So we return the third number.
Solution
1 |
|