-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path136.py
More file actions
58 lines (39 loc) · 988 Bytes
/
136.py
File metadata and controls
58 lines (39 loc) · 988 Bytes
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
'''
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
'''
#Solution-1 Using Loop
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
a = {}
f = {}
for i in nums:
if i not in a:
f[i] = f.get(i,0) + 1
if f[i] > 1:
a[i] = f[i]
f.pop(i)
return f.popitem()[0]
#Solution-2 Using XOR
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
t = 0
for i in nums:
t ^= i
return t