原文链接: http://hankerzheng.com/blog/Python-Hash-Heap
前言
LeetCode 480 Sliding Window Median 这题真是丧心病狂! 找中位数当然用Heap或者Balanced BST了, 然后Sliding Window当然需要支持Delete操作了. 好吧, 在Python中并没有自带的能同时支持两者的数据结构. 因此, 想在O(N logK)
的时间复杂度里面实现Sliding Window Median, 只能自己写一个数据结构了. 本文实现了Python中的Hash Heap数据结构, 并且附带简单的测试函数.
My Implementation of Other Data Structure and Algorithm - HankerZheng’s GitHub
Implementation Thoughts
基本的实现和普通的Heap没啥区别, 就是需要一个额外的HashMap
记录每个element的index, 然后每次做交换操作时, 不仅仅需要交换Heap中的位置, 还需要更新HashMap
中的值.
需要考虑一下的是, 如何处理Duplicates. 我采用的方法新建一个HeapNode
类, 该类能存当前元素的值以及相同值元素的个数, 这样在Heap
中, 就不会有Duplicats, 那么记录index的HashMap
就不会出现key
冲突的问题了.
Source Code
# This is the Python implementation of Hash Heap based on the list implementation
# of binary heap. The difference between Hash Heap and Binary Heap is that Hash
# Heap supports the `heapRemove` operation in O(log n) time and can check whether
# certain element is in the Hash Heap or not in O(1) time.
#
# Basic automatic tests are given in `pushpopTest()` and `removeTest()`.
# Note: It may takes about 10 seconds to run both test functions.
import random
class HeapNode(object):
"""
The node in the HashHeap to deal with duplicates.
Each node store the value of each element and the number of duplicates
with the same value.
"""
def __init__(self, val, cnt):
self.val = val
self.cnt = cnt
def __cmp__(self, other):
return self.val - other.val
def __str__(self):
return "[%s, %d]" % (self.val, self.cnt)
__repr__ = __str__
class HashHeap(object):
"""
This HashHeap is the same as the list implementation of binary heap, but with
a hashMap to map the value of one elemnt to its index in the list.
"""
def __init__(self, arr):
"""
`_cap` - the number of elements in the HashHeap
`_maxIdx` - the max index of the binary heap
`_data` -