题目链接
https://leetcode.com/problems/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?
思路方法
目的是寻找数组中单独出现的某个元素,如果题目没有限制条件很容易想到利用dict来做。然而既然要求O(n)的时间复杂度和O(1)的空间复杂度,那么就要想办法将成对出现的数“消掉”,目前能想到的就是利用“异或”操作实现。
思路一
将所有的数进行异或操作,由于题目说了只有一个单独出现的数,那么最终结果即为所求。
代码
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
res = 0
for i in nums:
res ^= i
return res
思路二
精简代码。。。
代码
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return reduce(lambda x, y: x^y, nums)
思路三
再精简代码。。。
代码
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return reduce(operator.xor, nums)
PS: 写错了或者写的不清楚请帮忙指出,谢谢!
转载请注明:http://blog.csdn.net/coder_orz/article/details/52064716