【发布时间】:2019-09-13 16:10:22
【问题描述】:
Hackerrank 哈希表出现“因超时而终止”错误:21 个测试用例中有 6 个的赎金记录
实现了开放地址散列。输入字符串的大小最大为 30,000 个字符串:已尝试将哈希表大小从 60,000 更改为 300,000,但没有成功。
CAPACITY = 300000
hashTable = [None] * CAPACITY
def checkMagazine(magazine, note):
# Store Magazine into hashtable
for element in magazine:
# print("STORED " + element)
position = calculateHash(element)
# print(position)
if hashTable[position] == None:
hashTable[position] = element
# print("Stored into " + str(position))
else:
i = 1
# print("collided into " + str((position) % CAPACITY))
while hashTable[(position + i) % CAPACITY] != None:
# print("collided into " + str((position + i) % CAPACITY))
i += 1
hashTable[(position + i) % CAPACITY] = element
# Check if all items in note is in hashtable
included = True
for item in note:
position = calculateHash(item)
if hashTable[position] != item:
i = 1
while hashTable[(position + i ) % CAPACITY] != item:
if hashTable[(position + i ) % CAPACITY] == None:
included = False
print("No")
return
else:
i += 1
hashTable[(position + i ) % CAPACITY] = "DONED"
else:
hashTable[position] = "DONED"
# print("Found " + item)
print("Yes")
def calculateHash(string):
return hash(string) % CAPACITY
鉴于哈希表是解决此问题的最佳方法(时间复杂度 O(n)),发生超时的原因是因为开放地址哈希吗?还是有其他原因?
【问题讨论】:
-
你指的是这个HackerRank question吗?如果是这样,那么解决它的方法要简单得多。
-
与上述内容相呼应,不清楚您是否尝试在 python 列表中实现哈希表作为自己的学习练习?如果没有,您应该知道您可以以类似的方式使用 Python 集,而代码显着 更少。
-
顺便说一下,如果您正在为自己的学习实现一个哈希表,我强烈建议您也将它封装在它自己的类中,这将有助于oyu考虑接口它需要提供。
-
不管怎样,我在没有散列或排序的情况下解决了这个问题,并且通过了所有测试而没有超时。