1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution:
def singleNumber(self, nums: List[int]) -> int:
ls=[]
x=0
counter=defaultdict(int)
for num in nums:
counter[num] += 1
if counter[num]>1:
ls.append(num)
nls= list(set(nums)-set(ls))
for i in nls:
x=i
return x

题解:异或运算

1
2
3
4
5
6
7
class Solution:
def singleNumber(self, nums: List[int]) -> List[int]:
x = 0
for num in nums: # 1. 遍历 nums 执行异或运算
x ^= num
return x; # 2. 返回出现一次的数字 x