题解 | #【模板】堆#

【模板】堆

https://www.nowcoder.com/practice/13f61c8c92404f5ea5d6fa4c692869fb

class MaxHeap():
    def __init__(self):
        self.heap = []
    
    def push(self, x):
        self.heap.append(x)
        self._sift_up(len(self.heap) - 1)
    
    def top(self):
        if len(self.heap) == 0:
            return 'empty'
        return self.heap[0]
    
    def pop(self):
        if len(self.heap) == 0:
            return 'empty'
        #将下层元素上浮到合适位置
        max_val = self.heap[0]
        last_val = self.heap.pop()
        
        if len(self.heap) > 0:
            self.heap[0] = last_val
            self._sift_down(0)
        
        return max_val
    #从给定位置向上移动元素,将给定索引i的元素与其父节点进行比较。如果当前元素大于其父节点,就交换它们的位置,使得当前元素上浮到更高的层级
    def _sift_up(self, i):
        while i > 0 and self.heap[i] > self.heap[(i - 1) // 2]:
            self.heap[i], self.heap[(i - 1) // 2] = self.heap[(i - 1) // 2], self.heap[i]
            #根据堆的完全二叉树特性,i的父节点索引值为(i - 1) // 2,向下取整
            i = (i - 1) // 2
    #从给定位置向下移动元素
    def _sift_down(self, i):
        max_idx = i
        #根据堆的完全二叉树特性,索引为i的节点的左子节点的索引是(2i + 1)
        left = 2 * i + 1
        right = 2 * i + 2
        
        if left < len(self.heap) and self.heap[left] > self.heap[max_idx]:
            max_idx = left
        
        if right < len(self.heap) and self.heap[right] > self.heap[max_idx]:
            max_idx = right
        
        if max_idx != i:
            self.heap[i], self.heap[max_idx] = self.heap[max_idx], self.heap[i]
            self._sift_down(max_idx)


n=input()
myheap=MaxHeap()
for i in range(int(n)):
    a=input().split()
    if a[0]=='push':
        myheap.push(int(a[1]))
    elif a[0]=='top':
         print(myheap.top()  )
    else:
        print(myheap.pop() )


全部评论

相关推荐

不愿透露姓名的神秘牛友
昨天 12:11
我最近都有点不想活了,天天早10晚11的,还问我爱不爱她目前的状态别说爱谁了,没扇谁就不错了。是不是大家都是一进节子,只有工作没有爱情了
AzureSkies:在字节的时候找的就是字节的,飞书太适合恋爱人士了,能看到是不是已读,是不是在会议中。简直冥婚好伴侣
投递字节跳动等公司9个岗位
点赞 评论 收藏
分享
05-19 19:57
蚌埠学院 Python
2237:Gpa70不算高,建议只写排名,个人技能不在多而在精,缩到8条以内。项目留一个含金量高的,减少间距弄到一页,硕士简历也就一页,本科不要写很多
实习,投递多份简历没人回...
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务