算法与数据结构 / 38

堆:实现、Top K与多路合并

数据结构、边界条件与实现过程。 堆:实现、Top K与多路合并。

阅读说明: 保留原笔记的编号与章节顺序;代码只供查看,没有在本站运行。历史输出不代表当前版本的复现结果。截图/外链图以独立整理的公式、表格、示意或文字替换;纠错与必要补充均作说明。

1. Heap property

Heap is a complete binary tree which is a binary tree in which level, except possibly the last, is the completely filled, and all nodes are as far left as possible.

  • min-heap: pop min number from the collection (每个node都比自己孩子节点小)
  • max-heap: pop max number from the collection (每个node都比自己孩子节点大)

整理注: 允许键相等时,小顶堆要求父节点不大于子节点,大顶堆不小于子节点;不是严格大小关系。

2. Implementation

数组与堆对应: 用层序数组表示完全树,0基索引i的左右孩子为2i+1、2i+2,父为(i−1)//2。最小堆只保证每条父子边有序,兄弟和不同子树不保证全局排序。

Array implementation: easy to store it as an array

  • left_child_node_index = parent_node_index * 2 + 1
  • right_child_node_index = parent_node_index * 2 + 2
  • parent_node_index = (child_node_index - 1) // 2

2.1 Array实现min heap

2.2.1 Push

  • push(9)

上浮轨迹: [0,1,5,6,8]追加9后父5≤9,无需交换;追加−1后先与父5交换,再与根0交换,得到[-1,1,0,6,8,5]。

PYTHON · 仅供阅读
arr = [0, 1, 5, 6, 8] -> push(9) -> arr = [0, 1, 5, 6, 8, 9]
  • push(-1)
PYTHON · 仅供阅读
arr = [0, 1, 5, 6, 8] -> push(-1) -> arr = [0, 1, 5, 6, 8, -1] -> arr = [-1, 1, 0, 6, 8, 5]

Sift-up operation:
TC=O(log⁡N)TC=O(\log{N})

PYTHON · 仅供阅读
class Heap(object):
    def __init__(self):
        self.array = []

    def sift_up(self, array, index):    
        parent_idx = (index - 1) // 2
        if parent_idx < 0 or array[index] > array[parent_idx]:
            return
        array[index], array[parent_idx] = array[parent_idx], array[index]
        self.sift_up(array, parent_idx)

    def push(self, val):
        self.array.append(val)
        self.sift_up(self.array, len(self.array) - 1)

2.2.2 Pop

  • pop()出0

下沉轨迹: 对[0,1,5,6,8,9]弹根0,将末尾9移到根,选较小孩子1交换,再与6交换,最终[1,6,5,9,8]。每层选择更小孩子以维持最小堆。

Sift-down operation:

  • Recursion: TC=O(log⁡N)TC=O(\log{N})
PYTHON · 仅供阅读
class Heap(object):
    def __init__(self):
        self.array = []

    def sift_down(self, array, index):
        left = index * 2 + 1
        right = index * 2 + 2
        small = index
        if left < len(array) and array[small] > array[left]:
            small = left
        if right < len(array) and array[small] > array[right]:
            small = right
        if small != index:
            array[small], array[index] = array[index], array[small]
            self.sift_down(array, small)

    def pop(self):
        res = self.array[0]
        self.array[0], self.array[-1] = self.array[-1], self.array[0]
        self.array.pop()  # O(1), pop(0)是O(n)
        self.sift_down(self.array, 0)  # O(logN)
        return res
  • iteration
PYTHON · 仅供阅读
def sift_down(self, array, index):
        left = index * 2 + 1
        right = index * 2 + 2
        while left < len(array):
            smaller = index
            if left < len(array) and array[smaller] > array[left]:
                smaller = left
            if right < len(array) and array[smaller] > array[right]:
                smaller = right
            if smaller == index:
                break
            array[index], array[smaller] = array[smaller], array[index]
            index = smaller
            left = index * 2 + 1
            right = index * 2 + 2

2.2.3 Heapify

Initialize a heap from a random array
[5, 4, 3, 2, 1] -> min-heap

  • The last element’s index is len(arr) - 1
  • The parent of this element is [(len(arr) - 1) - 1] // 2

TC=O(N)  not  O(NlogN)TC=O(N) \; \text{not} \; O(NlogN)
(0∗N/2)+(1∗N/4)+(2∗N/8)+…+(logN∗1)=O(N)(0 * N/2) + (1 * N/4) + (2 * N/8) + \ldots + (logN * 1) = O(N)

PYTHON · 仅供阅读
class Heap(object):
    def __init__(self):
        self.array = []

    def sift_down(self, array, index):
        left = index * 2 + 1
        right = index * 2 + 2
        small = index
        if left < len(array) and array[small] > array[left]:
            small = left
        if right < len(array) and array[small] > array[right]:
            small = right
        if small != index:
            array[small], array[index] = array[index], array[small]
            self.sift_down(array, small)

    def build_heap(self, arr):
        for i in range(len(arr)//2 - 1, -1, -1):
            self.sift_down(arr, i)

3. Python heapq library

  • heappush
PYTHON · 仅供阅读
import heapq

heap = []

heapq.heappush(heap, (-1, 2))
heapq.heappush(heap, (1, 3))
print(heap)  # [(-1, 2), (1, 3)]
heapq.heappush(heap, (-5, 6))
print(heap)  # [(-5, 6), (1, 3), (-1, 2)]
原笔记输出 · 本次未执行
[(-1, 2), (1, 3)]
[(-5, 6), (1, 3), (-1, 2)]
  • heappop()
PYTHON · 仅供阅读
print(heapq.heappop(heap))  # (-5, 6)
print(heap)  # [(-1, 2), (1, 3)]
原笔记输出 · 本次未执行
(-5, 6)
[(-1, 2), (1, 3)]
  • heapify()
PYTHON · 仅供阅读
heap = [6, 4, 5]
print(heapq.heapify(heap))  # None
print(heap)  # [4, 6, 5]
原笔记输出 · 本次未执行
None
[4, 6, 5]

4. Heapq questions

4.1 Find the smallest k elements from an unsorted array of size n

4.1.1 solution 1: min heap

  1. step 1: heapify all elements: O(N)
  2. step 2: call pop() k times to get the k smallest elements: O(k*logN)

total  TC=O(N+k∗log⁡N)\text{total} \; TC=O(N + k*\log{N})

PYTHON · 仅供阅读
import heapq

def kSmallest(array, k):
    if not array:
        return []
    res = []
    heapq.heapify(array)
    for i in range(min(k, len(array))):
        res.append(heapq.heappop(array))
    return res

4.1.2 solution 2: max heap

大小k的最大堆: 保存当前最小k个候选,堆顶是其中最大者。新值不小于堆顶就丢弃,否则替换堆顶;Python可用负数表示该最大堆。

Max heap of size k -> smallest k candidates

  1. step 1: heapify the first k elements to form a max-heap of size of k. TC=O(k)TC=O(k)
  2. step 2: Iterate over the rest (n-k) elements one by one
    When we traverse a new element, compare with the largest element of the previous smallest k candidates.
    • case 1: new element >= top: ignore
    • case 2: new element < top: update top -> new element. TC=O((n−k)∗log⁡k)TC=O((n-k)*\log{k})

total  TC=O(k+(n−k)∗log⁡k)\text{total} \; TC=O(k + (n-k)*\log{k})

PYTHON · 仅供阅读
def kSmallestII(array, k):
    if k <= 0:
        return []
    if not array:
        return array
    if k >= len(array):
        return array

    res = [-elem for elem in array[0:k]]
    heapq.heapify(res)
    for i in range(k, len(array)):
        if array[i] < -res[0]:
            heapq.heappop(res)
            heapq.heappush(res, -array[i])
    return [-elem for elem in res]

4.1.2 Compare two solutions

CompareO(N+k∗log⁡N)O(N + k*\log{N})O(k+(N−k)∗log⁡k)O(k + (N-k)*\log{k})
k<<Nk<<NO(N)O(N)O(N∗log⁡k)O(N*\log{k})
k∽Nk\backsim NO(N∗log⁡N)O(N*\log{N})O(N)O(N)

整理注: 复杂度比较应保留完整表达式;k接近n但不等于n时,(n-k)log k不能自动忽略。返回最小k项不一定有序。

4.2 Merge K sorted array

  • step 1: create a min heap, push the first element of each array into the heap
  • step 2: each time pops an element from the heap, and then push the next element into the heap
PYTHON · 仅供阅读
def mergek(arrays):
    if not arrays:
        return None
    heap = []
    for i in range(len(arrays)):
        # insert every first element in each array
        if len(arrays[i]):
            heap.append((arrays[i][0], i, 0))

    heapq.heapify(heap)
    result = []
    while heap:
        val, index_array, index_element = heapq.heappop(heap)
        result.append(val)
        if index_element + 1 < len(arrays[index_array]):
            heapq.heappush(heap, (arrays[index_array][index_element + 1], index_array, 
                                  index_element + 1))

    return result

# Test case
print(mergek([[2, 3, 7], [1, 3, 4], [3, 6, 9]]))
原笔记输出 · 本次未执行
[1, 2, 3, 3, 3, 4, 6, 7, 9]

整理参考资料