2020-04-01 08:15:56
Problem Description:
Given an array of integers, the stack operation is to put it into a minimum heap array.
For heap arrays A, A [0] is the root of the heap, and for each A [i], A [i * 2 + 1] is A [i] and the left son of A [i * 2 + 2] is A [i] right son.
Sample
输入 : [3,2,1,4,5] 输出 : [1,2,3,4,5] 解释 : 返回任何一个合法的堆数组
challenge
O (n) time complexity of the complete stack
Problem Solving:
Since the stack is its nature is a complete binary tree, then we can begin filtering downward from the non-leaf nodes, the specific operation from above is set to the minimum of the root.
By estimating the number of nodes per filter, i.e., n / 2 + n / 4 + ... + 1 = n.
Time complexity: O (n)
public void heapify(int[] A) { for (int i = A.length / 2; i >= 0; i--) { siftdown(A, i); } } private void siftdown(int[] A, int idx) { if (idx >= A.length) return; int k = idx; if (idx * 2 + 1 < A.length && A[idx * 2 + 1] < A[k]) k = idx * 2 + 1; if (idx * 2 + 2 < A.length && A[idx * 2 + 2] < A[k]) k = idx * 2 + 2; if (k == idx) return; int temp = A[idx]; A[idx] = A[k]; A[k] = temp; siftdown(A, k); }