题目如下:
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?
我的渣翻译如下:给你一个整形的数组,除了一个元素只出现一次,剩余每个元素都出现两次,找到那个单独的一个。
你的算法时间复杂度应该是O(n),你能不能不用额外的空间来完成。
精彩代码如下:
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 0: return
res = 0
for n in nums:
res ^= n
return res
巧妙利用异或运算,0^1^0 = 0^0^1 = 1 (^为异或运算符)
如:1,3,1
则001^011^001 = 011 = 3
所以最后的结果便是所要求的只出现一次的数字。
自己写的渣代码如下:
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
d = {};
for i in xrange(len(nums)):
if nums[i] not in d:
d[nums[i]] = nums[i];
else :
d.pop(nums[i]);
for i in d.values():
res = i
return res;
遍历list,数字第一次出现时候,便将其插入到字典中,第二次出现,则将其删除掉。这样最后字典中所剩的值便是所要求的。时间复杂度O(n),空间复杂度也是O(n)。很明显代码思维上还有一定的距离。。。