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

时间:2022-11-08 20:38:25

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 - ) / ; //父节点
int temp = a[i];
while(j >= && i != )
{
if(a[j] <= temp) break;
a[i] = a[j];
i = j;
j = (i - ) / ;
}
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 = * i + ;
int temp = a[i];
while(j < n)
{
if(j + < n && a[j + ] < a[j]) //在左右孩子中找最小的
j++;
if(a[j] >= temp)
break;
a[i] = a[j]; //把较小的子结点往上移动,替换它的父结点
i = j;
j = * i + ;
}
a[i] = temp;
} //在最小堆中删除数
void MinHeapDeleteNumber(int a[], int n)
{
swap(a[], a[n - ]);
MinHeapFixdown(a, , n - );
} int findKthLargest(vector<int>& nums, int k) {
int * a = new int[k]; //大小为k的最小堆
for(int i = ; i < nums.size(); ++i)
{
if(i < k)
{
MinHeapAddNumber(a, i, nums[i]); //插入数据
}
else if(nums[i] > a[]) //比已有的k个最大的数字大
{
MinHeapDeleteNumber(a, k);
MinHeapAddNumber(a, k - , nums[i]);
}
}
return a[];
}
};

用STL的堆:

 int findKthLargest(vector<int>& nums, int k) {
priority_queue<int> p;
const int s(nums.size()); for (int i = ; i < s; ++i) p.push(nums[i]);
while (--k) p.pop(); return p.top();
}

堆的相关讲解:

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