LintCode-堆化

来源:互联网 发布:c语言中goto是什么意思 编辑:程序博客网 时间:2024/05/29 04:58

给出一个整数数组,堆化操作就是把它变成一个最小堆数组。

对于堆数组A,A[0]是堆的根,并对于每个A[i],A [i * 2 + 1]是A[i]的左儿子并且A[i * 2 + 2]是A[i]的右儿子。

样例

给出 [3,2,1,4,5],返回[1,2,3,4,5] 或者任何一个合法的堆数组

挑战

O(n)的时间复杂度完成堆化

说明

什么是堆?

  • 堆是一种数据结构,它通常有三种方法:push, pop 和 top。其中,“push”添加新的元素进入堆,“pop”删除堆中最小/最大元素,“top”返回堆中最小/最大元素。

什么是堆化?

  • 把一个无序整数数组变成一个堆数组。如果是最小堆,每个元素A[i],我们将得到A[i * 2 + 1] >= A[i]和A[i  * 2 + 2] >= A[i]

如果有很多种堆化的结果?

  • 返回其中任何一个。

分析:一开始想到堆化么肯定就是堆排序吧,粗粗一想貌似复杂度是O(nlgn),后来参考该文章才知道O(nlgn)是复杂度上限,平均是O(n)

代码:

class Solution {public:    /**     * @param A: Given an integer array     * @return: void     */    void heapify(vector<int> &A) {        // write your code here        int n = A.size()-1;        for(int i=n/2;i>=0;i--)            heapify(A,i);    }    void heapify(vector<int> &A,int i)    {        int l = 2*i+1;        int r = 2*i+2;        int smallest = i;        if(l<A.size()&&A[l]<A[smallest])            smallest = l;        if(r<A.size()&&A[r]<A[smallest])            smallest = r;        if(smallest!=i)        {            swap(A[i],A[smallest]);            heapify(A,smallest);        }    }};


0 0