如何解决在 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,3]))
print(Solution().singleNumber([7,9,7]))
main()
返回结果为:
dict_keys([4])
dict_keys([9])
Process finished with exit code 0
我不确定是否有任何方法可以只返回数字,例如4
和 9
。感谢您的帮助。
解决方法
用 return hash.keys()
或 return hash.popitem()[0]
代替 return list(hash.keys())[0]
。
当然这假设哈希图中至少有一对。您可以在访问第一个元素之前使用 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,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,3]))
print(Solution().singleNumber([7,9,7]))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。