我正在研究一个问题:
In a non-empty array of integers, every number appears twice except for one, find that single number.
我试着通过哈希表来解决这个问题:
class Solution:
def singleNumber(self, array):
hash = {}
for i in array:
if i not in hash:
hash[i] = 0
hash[i] += 1
if hash[i] == 2:
del hash[i]
return hash.keys()
def main():
print(Solution().singleNumber([1, 4, 2, 1, 3, 2, 3]))
print(Solution().singleNumber([7, 9, 7]))
main()
返回结果为:
dict_keys([4])
dict_keys([9])
Process finished with exit code 0
我不确定是否有任何方法可以只返回数字,例如4
和9
。谢谢你的帮助。
用return hash.popitem()[0]
或return list(hash.keys())[0]
代替return hash.keys()
。
当然,这假设hashmap中至少有一对。您可以在访问第一个元素之前使用len(hash) > 0
检查这一点:
class Solution:
def singleNumber(self, array):
hash = {}
for i in array:
if i not in hash:
hash[i] = 0
hash[i] += 1
if hash[i] == 2:
del hash[i]
return hash.popitem()[0] if len(hash) > 0 else -1 # or throw an error
一个可能更简单的解决方案是使用.count
方法。
myList = [1, 4, 2, 1, 3, 2, 3]
non_repeating_numbers = []
for n in myList:
if myList.count(n) < 2:
non_repeating_numbers.append(n)
应用到你的代码中,它看起来像这样:
class Solution:
def singleNumber(self, array):
for n in array:
if array.count(n) < 2:
return n
def main():
print(Solution().singleNumber([1, 4, 2, 1, 3, 2, 3]))
print(Solution().singleNumber([7, 9, 7]))