您的位置:首页 > 其它

215题——Kth Largest Element in an Array(堆排序)

2015-07-28 15:38 573 查看

Kth Largest Element in an Array

Total Accepted: 13165 Total Submissions: 48240My Submissions
Question Solution

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.

Note:
You may assume k is always valid, 1 ≤ k ≤ array's length.

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

Hide Tags

Divide and Conquer Heap

Have you met this question in a real interview?
Yes

No

Discuss

这道题目的意思是找出数组中的第K大的数,可以采用堆排序的方法,采用最大堆,每次找出未排序的数组中的最大值

这里需要注意的时堆调整函数

#include<iostream>
#include<vector>
using namespace std;
//这里的数组第0位存储的数字没有用
/*用来交换数组中两个元素的值*/
void swaped(vector<int>& nums,int i,int j)
{
int temp;
temp=nums[i];
nums[i]=nums[j];
nums[j]=temp;
}
//在数组nums中,除了第s外的从s+1...m满足最大堆顺序
void heapsort(vector<int>& nums,int s,int m)
{
int temp,j;
temp=nums[s];
for(j=2*s;j<=m;j=2*j)
{
if(j<m&&nums[j]<nums[j+1])
j++;
if(temp>nums[j])
break;
nums[s]=nums[j];
s=j;
}
nums[s]=temp;
}
//主函数
int findkthLargest(vector<int>& nums,int k)
{
vector<int> vec;
int n=nums.size();
vec.push_back(0);
for(int i=0;i<n;i++)
vec.push_back(nums[i]);

for(int i=n/2;i>=1;i--)
{
heapsort(vec,i,n);
}
int re;
for(int i=n;i>=1;i--)
{
swaped(vec,1,i);
k--;
re=vec[i];
if(k==0)
break;
heapsort(vec,1,i-1);
}
return re;

}
int main()
{
cout<<"hello yanliang"<<endl;
int ary[10]={7,6,5,4,3,2,1};
vector<int> vec(ary,ary+7);
cout<<findkthLargest(vec,4)<<endl;

/*
for(int i=1;i<=4;i++)
cout<<vec[i]<<' ';
cout<<endl;

heapsort(vec,2,4);
for(int i=1;i<=4;i++)
cout<<vec[i]<<' ';
cout<<endl;

heapsort(vec,1,4);
for(int i=1;i<=4;i++)
cout<<vec[i]<<' ';
cout<<endl;
*/

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: