返回Python中哈希表中唯一的元素



我正在研究一个问题:

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

我不确定是否有任何方法可以只返回数字,例如49。谢谢你的帮助。

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]))

相关内容

  • 没有找到相关文章

最新更新