-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path136 Single Number.py
39 lines (33 loc) · 973 Bytes
/
136 Single Number.py
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
39
"""
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?
Author: Rajeev Ranjan
"""
class Solution:
def singleNumber(self, A):
"""
Cannot use hash table since extra memory
Use XOR instead
Algorithm:
Concept of RAID
XOR
bits:
consider a list of 4-bit number:
0000
0001
0010
...
1111
appear twice:
num^num is 0
storage ^= (num^num) is storage ^= 0, which is storage itself
if only appear once:
storage ^= num is the num, since the storage is 0 initially
:param A: a list of integer
:return: int
"""
storage = 0
for element in A:
storage ^= element # XOR
return storage