码迷,mamicode.com
首页 > 其他好文 > 详细

【leetcode】Kth Largest Element in an Array (middle)☆

时间:2015-05-24 23:25:35      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:

Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.

For example,
Given [3,2,1,5,6,4] and k = 2, return 5.

 

思路:

堆。讲解:二叉堆

class Solution {
public:
    //新插入i结点 其父节点为(i - 1) / 2
    void MinHeapFixup(int a[], int i) 
    {
        int j = (i - 1) / 2; //父节点
        int temp = a[i];
        while(j >= 0 && i != 0)
        {
            if(a[j] <= temp) break;
            a[i] = a[j];
            i = j;
            j = (i - 1) / 2;
        }
        a[i] = temp;
    }

    //在最小堆中插入新数据nNum
    void MinHeapAddNumber(int a[], int n, int nNum)
    {
        a[n] = nNum;
        MinHeapFixup(a, n);
    }

    //堆删除后的调整  从i节点开始调整,n为节点总数 从0开始计算 i节点的子节点为 2*i+1, 2*i+2
    void MinHeapFixdown(int a[], int i, int n)
    {
        int j = 2 * i + 1;
        int temp = a[i];
        while(j < n)
        {
            if(j + 1 < n && a[j + 1] < a[j]) //在左右孩子中找最小的
                j++;
            if(a[j] >= temp) 
                break;
            a[i] = a[j];  //把较小的子结点往上移动,替换它的父结点
            i = j;
            j = 2 * i  + 1;
        }
        a[i] = temp;
    }

    //在最小堆中删除数
    void MinHeapDeleteNumber(int a[], int n)
    {
        swap(a[0], a[n - 1]);
        MinHeapFixdown(a, 0, n - 1);
    }

    int findKthLargest(vector<int>& nums, int k) {
        int * a = new int[k]; //大小为k的最小堆
        for(int i = 0; i < nums.size(); ++i)
        {
            if(i < k)
            {
                MinHeapAddNumber(a, i, nums[i]); //插入数据
            }
            else if(nums[i] > a[0]) //比已有的k个最大的数字大
            {
                MinHeapDeleteNumber(a, k);
                MinHeapAddNumber(a, k - 1, nums[i]);
            }
        }
        return a[0];
    }
};

 

用STL的堆:

 int findKthLargest(vector<int>& nums, int k) {
    priority_queue<int> p;
    const int s(nums.size());

    for (int i = 0; i < s; ++i) p.push(nums[i]);
    while (--k) p.pop();

    return p.top();
}

堆的相关讲解:

http://www.cnblogs.com/flyoung2008/articles/2136485.html

【leetcode】Kth Largest Element in an Array (middle)☆

标签:

原文地址:http://www.cnblogs.com/dplearning/p/4526523.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!