Given a non-empty 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?
Example 1:
Input: [2,2,1] Output: 1
Example 2:
Input: [4,1,2,1,2] Output: 4
这个比较简单,思路:遍历列表保存到字典,当发现重复键,删除。这道题因为只有一个单一的数字,所以最后字典应该只剩下一个键值对。这个跟solution里的hash_tablehash\_table的的思路基本上是一样的,代码方面使用了复杂度更低一点的方法。直接使用try dict.pop()方式来判断这个值是否重复,时间空间复杂度为O(n * 1) = O(n)。而使用if i in dict,需要对字典进行遍历,复杂度取决于字典的长度。
class Solution:
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 0:
return 0
memo = {}
for i in nums:
if i in memo:
del memo[i]
else:
memo[i] = i
for s in memo.keys():
return s
Solution里最优的解题思路是使用二进制XOR运算,其时间复杂度是O(n),空间只有O(1)。
#以下代码来自https://leetcode.com/problems/single-number/solution/#
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
a = 0
for i in nums:
a ^= i
return a
这个方法在之前完全没想到。在XOR运算前将十进制数字转为二进制,然后根据XOR的运算规则,最后得到唯一数字。
a ⊕ 0 = a
a ⊕ a = 0
a ⊕ b ⊕ a = (a ⊕ a) ⊕ b = 0 ⊕ b = b
参考:https://leetcode.com/problems/single-number/solution/#