您的位置:首页 > 编程语言 > Python开发

[Leetcode]Single Number

2015-01-08 23:55 302 查看
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?

找到数组中只出现过一次的元素,其他元素都出现过两次~可以用位操作异或的性质, 因为两个相同的数异或的结果为0,可以对数组的所有元素进行异或,重复出现两次的元素会互相抵消,最后剩下的那个元素就是只出现一次的元素,时间复杂度为O(n)~

class Solution:
# @param A, a list of integer
# @return an integer
def singleNumber(self, A):
if A is None or len(A) == 0: return 0
res = A[0]
for i in xrange(1, len(A)):
res ^= A[i]
return res

还看到一个只有一行代码的python解法,代码如下~ reduce(func, A) 代表 func(func(A[0], A[1]), A[2])... 而operator模块提供了一系列的函数操作,比如,operator.add(x, y)等于x+y;operator.xor相当于x
^ y~所以下面的reduce function返回了A中所有元素的异或结果,也就是A中只出现了一次的元素~
class Solution:
# @param A, a list of integer
# @return an integer
def singleNumber(self, A):
return reduce(operator.xor, A)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode python