您的位置:首页 > 其它

leetcode|Single Number(136)

2015-12-05 22:37 429 查看
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?

way1:使用字典结构,记录每个单词出现的次数

class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
count = {}
for item in nums:
if item not in count:
count.setdefault(item,0)
count[item] += 1

for item in count:
if count[item] == 1:
return item

way2:使用异或逻辑特点,相同为0,相异为1。这个序列的数据有个特点,除了其中的一个只出现一次外,其它的数据都出现两次,所以当把这个序列的所有数据进行异或,就可以得到只出现一次那个数了。当然,这里面也很巧妙的使用了匿名函数lamda(我目前觉得该函数最大的好处就是不需要命函数名~)和函数式编程中的reduce
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return reduce(lambda x, y: x ^ y, nums)

参考资料: http://jeffxie.blog.51cto.com/1365360/328207  python内置函数map/reduce/filter

http://www.runoob.com/python/python-operators.html#ysf2  python运算符


http://woodpecker.org.cn/diveintopython/power_of_introspection/lambda_functions.html 使用lambda函数
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode