Medium Heapify
Given an integer array, heapify it into a min-heap array.
For a heap array A, A[0] is the root of heap, and for each A[i], A[i * 2 + 1] is the left child of A[i] and A[i * 2 + 2] is the right child of A[i].
Example
Given [3,2,1,4,5], return [1,2,3,4,5] or any legal heap array.
Challenge
O(n) time complexity
Clarification
What is heap?
- Heap is a data structure, which usually have three methods: push, pop and top. where "push" add a new element the heap, "pop" delete the minimum/maximum element in the heap, "top" return the minimum/maximum element.
What is heapify?
- Convert an unordered integer array into a heap array. If it is min-heap, for each element A[i], we will get A[i * 2 + 1] >= A[i] and A[i * 2 + 2] >= A[i].
想起了算法期中考试最后一题。。。刷题leetcode很多遍了,感觉leetcode有点进阶,这种基础的算法结构题都不收入。 这个题的模式是我的一个盲点。mark 一下
过俩天补上这题iterative的做法
public class Solution {
/**
* @param A: Given an integer array
* @return: void
*/
public void heapify(int[] A) {
// write your code here
for(int i = A.length/2; i>=0; i--){
helper(A,i);
}
}
public void helper(int[] A, int k){
if(k >= A.length)
return;
int left = 2*k+1 >= A.length? Integer.MAX_VALUE:A[2*k+1];
int right = 2*k+2 >= A.length? Integer.MAX_VALUE:A[2*k+2];
if(left < right && left < A[k]){
A[2*k+1] = A[k];
A[k] = left;
helper(A, 2*k+1);
}else if(right < A[k]){
A[2*k+2] = A[k];
A[k] = right;
helper(A, 2*k+2);
}
}
}