【面试】介绍堆及其时间复杂度(中英)

中文版

堆(Heap) 是一种特殊的树形数据结构,是完全二叉树的一种。堆分为两种类型:

  1. 最大堆(Max Heap):对于堆中的任意节点,其值都大于或等于其子节点的值。因此,最大值位于堆的根节点。
  2. 最小堆(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:

  1. 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.
  2. 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).
  • 5
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值