Python实现Hash Heap数据结构

本文介绍了为了解决LeetCode 480题——滑动窗口中位数问题,作者在Python中自创的一种Hash Heap数据结构。由于Python标准库没有提供同时支持查找中位数和删除操作的数据结构,作者通过在普通堆的基础上增加元素索引记录,并处理重复元素,实现了这一功能。文章包含了实现思路和源代码。
摘要由CSDN通过智能技术生成

原文链接: 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` -
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值