码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-07-28 17:45:12      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:

Kth Largest Element in an Array

 Total Accepted: 13165 Total Submissions: 48240My Submissions

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大的数,可以采用堆排序的方法,采用最大堆,每次找出未排序的数组中的最大值

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

 1 #include<iostream>
 2 #include<vector>
 3 using namespace std;
 4 //这里的数组第0位存储的数字没有用
 5 /*用来交换数组中两个元素的值*/
 6 void swaped(vector<int>& nums,int i,int j)
 7 {
 8     int temp;
 9     temp=nums[i];
10     nums[i]=nums[j];
11     nums[j]=temp;
12 }
13 //在数组nums中,除了第s外的从s+1...m满足最大堆顺序
14 void heapsort(vector<int>& nums,int s,int m)
15 {
16     int temp,j;
17     temp=nums[s];
18     for(j=2*s;j<=m;j=2*j)
19     {
20         if(j<m&&nums[j]<nums[j+1])
21             j++;
22         if(temp>nums[j])
23             break;
24         nums[s]=nums[j];
25         s=j;
26     }
27     nums[s]=temp;
28 }
29 //主函数
30 int findkthLargest(vector<int>& nums,int k)
31 {
32     vector<int> vec;
33     int n=nums.size();
34     vec.push_back(0);
35     for(int i=0;i<n;i++)
36         vec.push_back(nums[i]);
37 
38     for(int i=n/2;i>=1;i--)
39     {
40         heapsort(vec,i,n);
41     }
42     int re;
43     for(int i=n;i>=1;i--)
44     {
45         swaped(vec,1,i);
46         k--;
47         re=vec[i];
48         if(k==0)
49             break;
50         heapsort(vec,1,i-1);
51     }
52     return re;
53     
54 
55 }
56 int main()
57 {
58     cout<<"hello yanliang"<<endl;
59     int ary[10]={7,6,5,4,3,2,1};
60     vector<int> vec(ary,ary+7);
61     cout<<findkthLargest(vec,4)<<endl;
62 
63 /*
64     for(int i=1;i<=4;i++)
65         cout<<vec[i]<<‘ ‘;
66     cout<<endl;
67 
68     heapsort(vec,2,4);
69     for(int i=1;i<=4;i++)
70         cout<<vec[i]<<‘ ‘;
71     cout<<endl;
72 
73     heapsort(vec,1,4);
74     for(int i=1;i<=4;i++)
75         cout<<vec[i]<<‘ ‘;
76     cout<<endl;
77 */
78 
79 }

 

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

标签:

原文地址:http://www.cnblogs.com/yanliang12138/p/4682992.html

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