-
Notifications
You must be signed in to change notification settings - Fork 1
/
136-single_number.py
50 lines (42 loc) · 1.22 KB
/
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
40
41
42
43
44
45
46
47
48
49
50
"""
https://leetcode.com/problems/single-number/
Strat:
Run through list and map to dictionary. If a number hits the dictionary once,
then the number is the singleton.
Runtime: O(n)
64 ms, faster than 94.82% of Python online submissions for Single Number.
15.2 MB, less than 5.40% of Python online submissions for Single Number.
"""
class Solution(object):
"""
O(n) / linear time, O(n) / linear space
"""
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
set = {}
for num in nums:
if num in set:
set[num] = 1
else:
set[num] = 0
for num in set:
if set[num] == 0:
return num
"""
O(n) / linear time, O(1) space
From the leettcoode solution, using the xor operator
Good explaination: https://leetcode.com/problems/single-number/discuss/42997/My-O(n)-solution-using-XOR
essentially: ((2^2)^(1^1)^(4^4)^(5)) => (0^0^0^5) => 5
"""
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
a = 0
for i in nums:
a ^= i
return a