Return Python 中散列 table 中的唯一元素
Return the only element in the hash table in Python
我正在解决一个问题:
In a non-empty array of integers, every number appears twice except for one, find that single number.
我试着用哈希算出来 table:
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()
return结果为:
dict_keys([4])
dict_keys([9])
Process finished with exit code 0
我不确定是否有任何方法可以 return 只有数字,例如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, 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]))
我正在解决一个问题:
In a non-empty array of integers, every number appears twice except for one, find that single number.
我试着用哈希算出来 table:
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()
return结果为:
dict_keys([4])
dict_keys([9])
Process finished with exit code 0
我不确定是否有任何方法可以 return 只有数字,例如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, 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]))