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 SubmissionsQuestion 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; */ }
相关文章推荐
- git tag 相关操作
- springmvc 使用ajax报406错误
- sqlserver 评估期已过
- lnmp架构下php安全配置
- 数据结构——迷宫求解
- mp4文件格式解析
- Android Adapter接口
- 在Python中处理XML的教程
- poj-1328 Radar Installation--枚举
- SELECT INTO 和 INSERT INTO SELECT 两种表复制语句
- Qt4过渡至Qt5
- IOS开发之IOS8.0最新UIAlertController
- 测试大数据(快速排序)100万条数据
- Executor接口
- java中实现多线程
- php远程抓取函数curl(),file_get_contents
- Mat矩阵的初始化
- C#中结构类型和类类型
- spring mvc 后台获取不到form提交的参数
- mybatis入门基础(八)-----查询缓存