#130 Heapify
来源:互联网 发布:gopro6照片软件 编辑:程序博客网 时间:2024/04/29 02:42
题目描述:
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.
这题给了提示说是A满足:A[i * 2 + 1] >= A[i] and A[i * 2 + 2] >= A[i]。这样,我们就可以把A的前半部分的每个i遍历一遍,对于每个i来说,如果不满足这样的关系式,就在它的子heap中找出最小值,然后将i和最小值对应的坐标smallest互换。然后check i在它的新位置是不是满足heap的关系,不行再互换,一直把i换到它应该在的位置为止。
同时,我们要注意遍历i的时候要从A.size() / 2往前遍历,否则,后面的互换操作会打乱前面已经换好的那些。
Mycode(AC = 238ms):
class Solution {public: /** * @param A: Given an integer array * @return: void */ void heapify(vector<int> &A) { // write your code here for (int i = A.size() / 2; i >= 0; i--) { sift_down(A, i); } } void sift_down(vector<int> &A, int k) { int idx = k; while (idx < A.size()) { int smallest = idx; // find the smallest number among its subheap if (idx * 2 + 1 < A.size() && A[idx * 2 + 1] < A[smallest]) { smallest = idx * 2 + 1; } if (idx * 2 + 2 < A.size() && A[idx * 2 + 2] < A[smallest]) { smallest = idx * 2 + 2; } if (smallest != idx) { swap(A, smallest, idx); } else { break; } idx = smallest; } } void swap(vector<int> &A, int i, int j) { int tmp = A[i]; A[i] = A[j]; A[j] = tmp; }};
0 0
- #130 Heapify
- Heapify
- Lintcode - Heapify
- [刷题]Heapify
- lintcode:Heapify
- LintCode_130 Heapify
- 大根堆 - max heapify
- heapify的总结
- *[Lintcode] Heapify 堆化
- 数组建堆(heapify)
- Lintcode130 Heapify solution 题解
- max-heapify的运行时间分析
- 堆排序之MAX-HEAPIFY注释
- 130.Heapify-堆化(中等题)
- 最大堆维护,MAX-HEAPIFY非递归伪代码
- W. :MAX-HEAPIFY,6-2中描述的子过程,P75.
- 第六章堆排序之“保持堆的性质MAX-HEAPIFY”(递归版)
- 第六章堆排序之“保持堆的性质MAX-HEAPIFY”(迭代版,练习6.2-5)
- rsyslog 同时发生nginx 访问日志和错误日志
- 实地址模式与保护模式下的中断与异常处理
- CentOS6.5下搭建Samba服务器
- 8.6 子模块分析之CM
- 自己实现一个Native方法的调用
- #130 Heapify
- (后台学习阶段)SpringMvc(一)Eclipse搭建web项目
- com/android/dx/command/Main : Unsupported major.minor version 52.0
- 我的见解之hibernate(七)
- Android Studio打造自己的Live Templates
- Maven学习总结(三)——使用Maven构建项目
- Android_DES加密,密钥不变
- 在线工具和云服务推荐
- 我是shunliban,刚来到csdn博客 大家多给提建议~