我正试图在HackerRank中使用python解决堆数据结构问题。
我用两种方法实现了它
第一个
from heapq import heappush,heappop
heap = []
deleted_nodes = []
num_of_entries = int(input())
for i in range(num_of_entries):
line = list(map(int, input().strip().split(' ')))
if line[0] == 1:
heappush(heap,line[1])
elif line[0] == 2:
if heap[0] == line[1]:
heappop(heap)
else:
heappush(deleted_nodes,line[1])
elif line[0] == 3:
check = bool(deleted_nodes)
while check:
if deleted_nodes[0] == heap[0]:
heappop(heap)
heappop(deleted_nodes)
check = bool(deleted_nodes)
else:
check = False
print(heap[0])
第二个
from heapq import heappush,heappop
class Heap:
def __init__(self):
self.heap = []
self.deleted_nodes = []
def delete(self,value):
if self.heap[0] == value:
heappop(self.heap)
else:
heappush(self.deleted_nodes,value)
def get_min(self):
check = bool(self.deleted_nodes)
while check:
if self.deleted_nodes[0] == self.heap[0]:
heappop(self.heap)
heappop(self.deleted_nodes)
check = bool(self.deleted_nodes)
else:
check = False
print(self.heap[0])
if __name__ == "__main__":
heap = Heap()
num_of_entries = int(input())
for i in range(num_of_entries):
line = input().strip().split(' ')
line = list(map(int,line))
if line[0] == 1:
heappush(heap.heap,line[1])
elif line[0] == 2:
heap.delete(line[1])
elif line[0] == 3:
heap.get_min()
第一个成功通过了所有测试用例。
第二个通过了超过一半的测试用例,其余部分不断出现运行时错误
我真的不明白为什么会这样。
PS:大多数失败的测试用例包含超过10000个值。你知道吗
看来我应该通过
我换了几行,它通过了所有的测试。你知道吗
相关问题 更多 >
编程相关推荐