Lintcode - Heapify
2015-02-08 08:34
253 查看
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].
思路:从下往上heapify,如果两个子节点都比母节点小,那么就swap最小的那个。swap之后,我们要重新heapify 被换的节点(曾经的母节点,现在的子节点)
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].
思路:从下往上heapify,如果两个子节点都比母节点小,那么就swap最小的那个。swap之后,我们要重新heapify 被换的节点(曾经的母节点,现在的子节点)
public void heapify(int[] A) { for (int i = A.length / 2-1; i >= 0; i--) { helper(A, i); } } void helper(int[] A, int i) { int left = i * 2 + 1 >= A.length ? Integer.MAX_VALUE : A[2*i+1]; int right = i * 2 + 2 >= A.length ? Integer.MAX_VALUE : A[2*i+2]; if (left < right && left < A[i]) { A[2*i+1] = A[i]; A[i] = left; helper(A, 2*i+1); } else if (right < A[i]) { A[2*i+2] = A[i]; A[i] = right; helper(A, 2*i+2); } }
相关文章推荐
- Lintcode: Heapify && Summary: Heap
- lintcode:Heapify
- LintCode "Heapify"
- LintCode Heapify
- 一起lintcode ------- 二分查找看这篇就够了
- LintCode题解之统计数字
- LintCode之5 第k大元素
- Lintcode90 K Sum || solution 题解
- Lintcode 3统计数字
- lintcode&九章算法——No.11 二叉查找树中搜索区间 ? 待解决
- Lintcode主元素问题
- lintcode-easy-Unique Paths
- Lintcode:合并排序数组
- Lintcode:平面列表
- LintCode : 将整数A转换为B
- lintcode:带环链表
- lintcode 3:统计数字
- LintCode-Sort Letters by Case
- lintcode-二叉树的最小深度-155
- LintCode python 小白-简单题-2 尾部的0