-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSingle Number.py
More file actions
36 lines (30 loc) · 948 Bytes
/
Copy pathSingle Number.py
File metadata and controls
36 lines (30 loc) · 948 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
# Single Number
#
# Given an 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?
class Solution:
#解法一 异或运算符
# @param A, a list of integer
# @return an integer
def singleNumber(self, A):
result = 0
for i in A:
# 相同元素异或为0,0与任何数异或等于任何数,有a^b^a = b
# 此外,异或还可以用于两个元素交换a=a^b^(b=a)
result = result^i
return(result)
class Solution:
# 解法二
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
d = {}
for n in nums:
d[n] = d.get(n, 0) + 1
for k, v in d.items():
if v == 1:
return k