-
Notifications
You must be signed in to change notification settings - Fork 0
/
Single_Number
38 lines (31 loc) · 917 Bytes
/
Single_Number
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/*
Single Number
Given an 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?
*/
class Solution {
public:
int singleNumber(int A[], int n) {
if (n==0) return A[0];
int res = A[0];
for (int i=1; i<n; ++i)
{
res = res ^ A[i];
}
return res;
}
};
REMARK:
1.Have no idea. How to do that in O(n) time without using extra memory?
IDEA:
The requirement is O(n) time and O(1) space.
Thus, the "first sort and then find " way is not working.
Also the "hash map" way is not working.
Thus, we use XOR: a XOR a = 0, a XOR b XOR a = b
(Note: for XOR, we have:
(1)Commutativity: a XOR b = b XOR a
(2)Associativity: (a XOR b) XOR c = a XOR (b XOR c)
(3)
)
By using XOR, the code becomes very easy. But hard to think of XOR.