136. 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?

 

 1 class Solution(object):
 2     def singleNumber(self, nums):
 3         """
 4         :type nums: List[int]
 5         :rtype: int
 6         """
 7         dic = {}
 8         for num in nums:
 9             dic[num] = dic.get(num, 0)+1
10         for key, val in dic.items():
11             if val == 1:
12                 return key 

dic.get(num,0) 对键num来说,如果它出现在字典里,返回它对应的值;如果没有,返回default定义的值

dic.items()返回键值对

 

 1 class Solution(object):
 2     def singleNumber(self, nums):
 3         """
 4         :type nums: List[int]
 5         :rtype: int
 6         """
 7         res = 0
 8         for num in nums:
 9             res ^= num
10         return res 

^=按位异或

 

1 class Solution(object):
2     def singleNumber(self, nums):
3         """
4         :type nums: List[int]
5         :rtype: int
6         """
7         return 2*sum(set(nums))-sum(nums)

set()变成集合,集合是无序不重复集

 

1 class Solution(object):
2     def singleNumber(self, nums):
3         """
4         :type nums: List[int]
5         :rtype: int
6         """
7         return reduce(lambda x, y: x ^ y, nums)

python中的reduce内建函数是一个二元操作函数,他用来将一个数据集合(链表,元组等)中的所有数据进行下列操作:用传给reduce中的函数 func()(必须是一个二元操作函数)先对集合中的第1,2个数据进行操作,得到的结果再与第三个数据用func()函数运算,最后得到一个结果。

 

1 class Solution(object):
2     def singleNumber(self, nums):
3         """
4         :type nums: List[int]
5         :rtype: int
6         """
7         return reduce(operator.xor, nums)

 

转载于:https://www.cnblogs.com/fullest-life/p/6591195.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值