实现一个具有最大堆/最小堆功能的数据结构。

实现一个具有最大堆/最小堆功能的数据结构

为了实现一个具有最大堆/最小堆功能的数据结构,我们可以使用数组来存储堆结构,并提供一系列操作来维护堆的性质。

具体实现可以包括以下几个要点:

  1. 堆的插入操作:将新元素添加到堆的末尾,然后通过上浮操作使其满足最大堆/最小堆的性质。

  2. 堆的删除操作:删除堆顶元素,将堆的最后一个元素移到堆顶,然后通过下沉操作使其满足最大堆/最小堆的性质。

  3. 堆的构建:从一个无序数组构建一个最大堆/最小堆。

  4. 获取堆顶元素:获取堆中的最大元素或最小元素(取决于是最大堆还是最小堆)。

以下是一个示例实现:

class Heap:
    def __init__(self, is_max_heap=True):
        self.heap = []
        self.is_max_heap = is_max_heap

    # 堆的插入操作
    def insert(self, val):
        self.heap.append(val)
        self._sift_up(len(self.heap) - 1)

    # 上浮操作
    def _sift_up(self, idx):
        while idx > 0:
            parent = (idx - 1) // 2
            if (self.is_max_heap and self.heap[idx] > self.heap[parent]) or (not self.is_max_heap and self.heap[idx] < self.heap[parent]):
                self.heap[idx], self.heap[parent] = self.heap[parent], self.heap[idx]
                idx = parent
            else:
                break

    # 堆的删除操作
    def remove(self):
        if not self.heap:
            return None
        if len(self.heap) == 1:
            return self.heap.pop()
        root = self.heap[0]
        self.heap[0] = self.heap.pop(-1)
        self._sift_down(0)
        return root

    # 下沉操作
    def _sift_down(self, idx):
        while 2 * idx + 1 < len(self.heap):
            child = 2 * idx + 1
            if child + 1 < len(self.heap) and ((self.is_max_heap and self.heap[child] < self.heap[child + 1]) or (not self.is_max_heap and self.heap[child] > self.heap[child + 1])):
                child += 1
            if (self.is_max_heap and self.heap[child] > self.heap[idx]) or (not self.is_max_heap and self.heap[child] < self.heap[idx]):
                self.heap[idx], self.heap[child] = self.heap[child], self.heap[idx]
                idx = child
            else:
                break

# 示例使用最大堆
max_heap = Heap()
max_heap.insert(4)
max_heap.insert(10)
max_heap.insert(8)
max_heap.insert(5)
print(max_heap.remove())  # 输出: 10

# 示例使用最小堆
min_heap = Heap(is_max_heap=False)
min_heap.insert(4)
min_heap.insert(10)
min_heap.insert(8)
min_heap.insert(5)
print(min_heap.remove())  # 输出: 4

在上述示例中,我们创建了一个名为Heap的类,其中包含了插入、删除、上浮和下沉等方法,以及示例使用最大堆和最小堆的情况。