-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path136_SingleNumber.py
83 lines (61 loc) · 2.15 KB
/
136_SingleNumber.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
72
73
74
75
76
77
78
79
80
81
82
83
#-------------------------------------------------------------------------------
#
#-------------------------------------------------------------------------------
# By Will Shin
#
#-------------------------------------------------------------------------------
# LeetCode prompt
#-------------------------------------------------------------------------------
"""
136. Single Number
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
"""
# #
#-------------------------------------------------------------------------------
# Approach
#-------------------------------------------------------------------------------
"""
create dict.
* not in dict, then add
* if in dict, then remove
* 1 remaining number returned
"""
#-------------------------------------------------------------------------------
# Solution
#-------------------------------------------------------------------------------
def mysingleNumber(nums):
my_hashmap = {}
for num in nums:
if num not in my_hashmap.keys():
my_hashmap[num] = '1'
else:
del my_hashmap[num]
return([*my_hashmap])
#-------------------------------------------------------------------------------
# Main Leetcode Input Driver
#-------------------------------------------------------------------------------
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return mysingleNumber(nums)
#-------------------------------------------------------------------------------
# Unit Test
#-------------------------------------------------------------------------------
import unittest
class TestSolution(unittest.TestCase):
def test_1(self):
self.assertEqual(Solution().singleNumber([2, 2, 1]), [1])
def test_2(self):
self.assertEqual(Solution().singleNumber([4, 1, 2, 1, 2]), [4])
unittest.main()