在 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

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

解决方法

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