-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0136_single_number.py
More file actions
79 lines (62 loc) · 1.85 KB
/
0136_single_number.py
File metadata and controls
79 lines (62 loc) · 1.85 KB
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#------------------------------------------------------------------------------
# Question:
#------------------------------------------------------------------------------
# tags:
'''
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:
Input: [2,2,1]
Output: 1
Example 2:
Input: [4,1,2,1,2]
Output: 4
'''
#------------------------------------------------------------------------------
# Solutions
#------------------------------------------------------------------------------
from typing import *
import functools
class Solution:
'''
Time: O(n)
Space: O(n)
'''
def singleNumber(self, nums: List[int]) -> int:
h = {}
for n in nums:
h[n] = False if n not in h else not(h[n])
single = [n for n in h if h[n] is False]
return(single[0])
class Solution2:
'''
Time: O(n)
Space: O(n)
'''
def singleNumber(self, nums: List[int]) -> int:
bit = 0
for n in nums:
bit ^= n
return bit
# return functools.reduce(lambda x,y: x^y, nums)
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
import unittest
class TestSolution(unittest.TestCase):
def test_simple(self):
nums = [2,2,1]
s = Solution()
self.assertEqual(s.singleNumber(nums), 1)
s = Solution2()
self.assertEqual(s.singleNumber(nums), 1)
def test_simple2(self):
nums = [4,1,2,1,2]
s = Solution()
self.assertEqual(s.singleNumber(nums), 4)
s = Solution2()
self.assertEqual(s.singleNumber(nums), 4)
unittest.main(verbosity=2)