您的位置:首页 > 其它

【LEETCODE】136-Single Number

2015-12-28 15:09 148 查看
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.建立dict,数每个元素出现的次数,返回次数为1的元素
2.位操作:
参考:http://www.cnblogs.com/zuoyuan/p/3719584.html
异或操作具有这两个特点,x ^ 0 = x,x ^ x = 0,并且与先后顺序无关,
所以出现两次的都会变成0,0再和出现一次的异或,剩下它自己



方法1:
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""

A={}

#for i in range(len(nums)):
#    if nums[i] not in A:
#        A[nums[i]]=1
#    else:
#        A[nums[i]]=2

for i in nums:
if i not in A:
A[i]=1
else:
A[i]=2

for j in A:
if A[j]==1:
return j


方法2:
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""

ans=nums[0]

for i in range(1,len(nums)):
ans=ans^nums[i]

return ans
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: