136. Single Number Easy
Description
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
- Example 1:
Input: [2,2,1]
Output: 1
- Example 2:
Input: [4,1,2,1,2]
Output: 4
题意
求一非空数组中只出现一次的数
解题思路
最开始是想用字典dict比较方便,而题目要求时间复杂度为O(n),且不借助辅助空间。参考异或的解法,也很方便。
笔记:
^ :按位异或运算符:当两对应的二进位相异时,结果为1。
示例:
a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
c = 0c = a ^ b; # 49 = 0011 0001
print(“3 - c 的值为:”, c)
c 的值为: 49
dict code
class Solution:
def singleNumber(self, nums: List[int]) -> int:
if nums == []:
return 0
dic = collections.defaultdict(int)
for i in nums:
dic[i] += 1
print(dic)
for key,value in dic.items():
if value % 2 != 0:
return key
异或 code
class Solution:
def singleNumber(self, nums: List[int]) -> int:
if nums == []:
return 0
res = 0
for num in nums:
res = res ^ num
return res