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)

 

posted on 2017-03-20 19:38  Ci_pea  阅读(153)  评论(0编辑  收藏  举报