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].
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].
What if there is a lot of solutions?
- Return any of them.
Example
Given [3,2,1,4,5], return [1,2,3,4,5] or any legal heap array.
Challenge
另外一个计算时间复杂度的链接
O(n) time complexity
class Solution {
private:
void swap(vector<int> &A, int i, int j) {
int tmp = A[i];
A[i] = A[j];
A[j] = tmp;
}
void heapifyHelper(vector<int> &A, int i)
{
int left = i*2+1;
int right = i*2+2;
int smallest = i;
// find the smallest element and then swap with parent
if (left<A.size() && A[left]<A[smallest])
smallest = left;
if (right<A.size() && A[right]<A[smallest])
smallest = right;
// this process would be loop to the button
if (i != smallest)
{
swap(A, i, smallest);
heapifyHelper(A, smallest);
}
}
public:
/**
* @param A: Given an integer array
* @return: void
*/
void heapify(vector<int> &A) {
// write your code here
int lastIdx = A.size()-1;
int parentIdx=0;
// try to find the last parent layer
if (lastIdx % 2 == 0)
parentIdx = (lastIdx-2)/2;
else
parentIdx = (lastIdx-1)/2;
// loop from the last parent to top
for (int i=parentIdx; i>=0; i--)
heapifyHelper(A, i);
}
};
另外一个计算时间复杂度的链接
http://blog.csdn.net/mtawaken/article/details/7964914