Heapify

Question

  1. Given an integer array, heapify it into a min-heap array.
  2. For a heap array A, A[0] is the root of heap, and for each A[i],
  3. A[i * 2 + 1] is the left child of A[i] and A[i * 2 + 2] is the right child of A[i].
  4. Example
  5. Given [3,2,1,4,5], return [1,2,3,4,5] or any legal heap array.
  6. Challenge
  7. O(n) time complexity
  8. Clarification
  9. What is heap?
  10. Heap is a data structure, which usually have three methods: push, pop and top.
  11. where "push" add a new element the heap,
  12. "pop" delete the minimum/maximum element in the heap,
  13. "top" return the minimum/maximum element.
  14. What is heapify?
  15. Convert an unordered integer array into a heap array.
  16. If it is min-heap, for each element A[i],
  17. we will get A[i * 2 + 1] >= A[i] and A[i * 2 + 2] >= A[i].
  18. What if there is a lot of solutions?
  19. Return any of them.

题解

参考前文提到的 Heap Sort 可知此题要实现的只是小根堆的堆化过程,并不要求堆排。

C++

  1. class Solution {
  2. public:
  3. /**
  4. * @param A: Given an integer array
  5. * @return: void
  6. */
  7. void heapify(vector<int> &A) {
  8. // build min heap
  9. for (int i = A.size() / 2; i >= 0; --i) {
  10. min_heap(A, i);
  11. }
  12. }
  13. private:
  14. void min_heap(vector<int> &nums, int k) {
  15. int len = nums.size();
  16. while (k < len) {
  17. int min_index = k;
  18. // left leaf node search
  19. if (k * 2 + 1 < len && nums[k * 2 + 1] < nums[min_index]) {
  20. min_index = k * 2 + 1;
  21. }
  22. // right leaf node search
  23. if (k * 2 + 2 < len && nums[k * 2 + 2] < nums[min_index]) {
  24. min_index = k * 2 + 2;
  25. }
  26. if (k == min_index) {
  27. break;
  28. }
  29. // swap with the minimal
  30. int temp = nums[k];
  31. nums[k] = nums[min_index];
  32. nums[min_index] = temp;
  33. // not only current index
  34. k = min_index;
  35. }
  36. }
  37. };

源码分析

堆排的简化版,最后一步k = min_index不能忘,因为增删节点时需要重新建堆,这样才能保证到第一个节点时数组已经是二叉堆。

复杂度分析

由于采用的是自底向上的建堆方式,时间复杂度为 (N), 证明待补充…

Reference