-
Notifications
You must be signed in to change notification settings - Fork 29
/
0136-Single-Number.py
71 lines (52 loc) · 1.39 KB
/
0136-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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
'''
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
'''
from typing import List
# Bit Manipulation
# Time Complexity: O(n)
# Space Complexity: O(1)
class Solution:
def singleNumber(self, nums: List[int]) -> int:
res = 0
for num in nums:
res ^= num
return res
# Hash Set
# Time Complexity: O(n)
# Space Complexity: O(n)
class Solution:
def singleNumber(self, nums: List[int]) -> int:
unique = set()
for num in nums:
unique.add(num)
return (2 * sum(unique)) - sum(nums)
# Hash Set One Liner
class Solution:
def singleNumber(self, nums: List[int]) -> int:
return 2*(sum(set(nums))) - sum(nums)
# Hash Table
# Time Complexity: O(n)
# Space Complexity: O(n)
class Solution:
def singleNumber(self, nums: List[int]) -> int:
unique = {}
for num in nums:
if num in unique:
unique[num] += 1
else:
unique[num] = 1
for key, value in unique.items():
if value == 1:
return key
# Check Custom Input
s = Solution()
answer = s.singleNumber([3, 3, 2, 2, 1]) # 1
print(answer)