中文版
堆(Heap) 是一种特殊的树形数据结构,是完全二叉树的一种。堆分为两种类型:
- 最大堆(Max Heap):对于堆中的任意节点,其值都大于或等于其子节点的值。因此,最大值位于堆的根节点。
- 最小堆(Min Heap):对于堆中的任意节点,其值都小于或等于其子节点的值。因此,最小值位于堆的根节点。
时间复杂度:
- 插入(Insert):将一个新元素插入堆的时间复杂度为 O ( log n ) O(\log n) O(logn),因为插入操作需要维护堆的性质。
- 删除最大/最小值(Delete Max/Min):删除堆顶元素(即最大堆的最大值或最小堆的最小值)的时间复杂度为 O ( log n ) O(\log n) O(logn),因为需要调整堆以维持其结构。
- 建堆(Build Heap):将一个无序数组转换为堆的时间复杂度为 O ( n ) O(n) O(n)。
- 堆排序(Heap Sort):堆排序的时间复杂度为 O ( n log n ) O(n \log n) O(nlogn)。
English Version
A Heap is a special tree-based data structure, which is a type of complete binary tree. There are two types of heaps:
- Max Heap: In a max heap, the value of each node is greater than or equal to the values of its children. Hence, the maximum value is at the root of the heap.
- Min Heap: In a min heap, the value of each node is less than or equal to the values of its children. Hence, the minimum value is at the root of the heap.
Time Complexity:
- Insertion: The time complexity for inserting a new element into a heap is O ( log n ) O(\log n) O(logn), because the heap property must be maintained during the insertion.
- Delete Max/Min: The time complexity for deleting the root element (i.e., the maximum in a max heap or the minimum in a min heap) is O ( log n ) O(\log n) O(logn), as the heap needs to be adjusted to maintain its structure.
- Build Heap: The time complexity for converting an unordered array into a heap is O ( n ) O(n) O(n).
- Heap Sort: The time complexity for heap sort is O ( n log n ) O(n \log n) O(nlogn).