最大堆疊

最大堆疊(Max-Stack)是一種數據結構,它結合了堆棧和堆的功能。最大堆疊支持兩種操作:push(壓入)和 popMax(彈出最大值)。

堆棧是一種後進先出(LIFO)的數據結構,而堆是一種儲存數字序列的數據結構,其中每個節點的值都不小於其子節點的值(對於最大堆)。

最大堆疊的工作原理是,當一個數字被push到堆疊中時,它也會被加入到一個最大堆中。當我們需要popMax時,我們實際上是在最大堆中找到最大值,並將其從堆中移除。

以下是最大堆疊的一些特點:

  1. 最大堆疊支持push操作,這會將一個數字壓入堆棧並加入到最大堆中。
  2. 最大堆疊支持popMax操作,這會從最大堆中彈出最大值,並將其從堆棧中移除。
  3. 最大堆疊中的數字會保持堆的特性,即每個節點的值都不小於其子節點的值。
  4. 最大堆疊可以幫助我們在O(1)時間內找到最大值,因為最大值總是在堆頂。

以下是一個簡單的Python實現:

class MaxStack:
    def __init__(self):
        self.stack = []
        self.max_heap = []

    def push(self, value):
        self.stack.append(value)
        self.max_heap.append(value)
        self.bubble_up(len(self.max_heap) - 1)

    def popMax(self):
        if not self.max_heap:
            return None
        max_val = self.max_heap[0]
        self.max_heap[0] = self.max_heap.pop()
        if self.max_heap:
            self.max_heap[0] = self.stack.pop()
            self.max_heap = self.heapify_down(0)
        return max_val

    def bubble_up(self, i):
        while i // 2 > 0 and self.max_heap[i] > self.max_heap[i // 2]:
            self.swap(i, i // 2)
            i = i // 2

    def swap(self, i, j):
        self.stack[i], self.stack[j] = self.stack[j], self.stack[i]
        self.max_heap[i], self.max_heap[j] = self.max_heap[j], self.max_heap[i]

    def heapify_down(self, i):
        while 2 * i <= len(self.max_heap) - 1:
            j = 2 * i
            if j < len(self.max_heap) - 1 and self.max_heap[j] < self.max_heap[j + 1]:
                j += 1
            if self.max_heap[i] <= self.max_heap[j]:
                break
            self.swap(i, j)
            i = j
        return self.max_heap

# 使用示例
max_stack = MaxStack()
max_stack.push(2)
max_stack.push(1)
max_stack.push(3)
print(max_stack.popMax())  # 輸出: 3
print(max_stack.popMax())  # 輸出: 2
print(max_stack.popMax())  # 輸出: 1

這個實現使用了兩個內部列表:self.stack 用於實際的堆棧操作,self.max_heap 用於保持堆的特性。push 方法會將數字壓入堆棧並加入到最大堆中,popMax 方法會從最大堆中彈出最大值並將其從堆棧中移除。bubble_upheapify_down 方法用於保持最大堆的特性。