# LeetCode215:Kth Largest Element in an Array

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

# 解法一：使用最小堆

runtime:8ms

    int findKthLargest(vector<int>& nums, int k) {
make_heap(nums.begin(),nums.begin()+k,greater<int>());
for(int i=k;i<nums.size();i++)
{
int top=nums.front();
if(nums[i]>top)
{
pop_heap(nums.begin(),nums.begin()+k,greater<int>());
nums[k-1]=nums[i];
push_heap(nums.begin(),nums.begin()+k,greater<int>());
}
}
return nums.front();
}

# 解法二：使用最大堆

runtime:8ms

    int findKthLargest(vector<int>& nums, int k) {
make_heap(nums.begin(), nums.end());
for (int i=1; i<k; i++){
pop_heap(nums.begin(), nums.end());
nums.pop_back();
}
return nums[0];
}

# 解法三：分治法

1. 小于关键元素pivot的元素
2. 等于关键元素pivot的元素
3. 大于关键元素pivot的元素

1. 初始化left为0，right为nums.size()-1
2. 分割数组，如果pivot在第k-1位，返回pivot
3. 如果pivot在k-1右边，更新right为pivot的位置值
4. 否则更新left为pivot的位置值。
5. 重复2的步骤

runtime:8ms

     int findKthLargest(vector<int>& nums, int k) {
int pivot=nums[0];
int left=0;
int right=nums.size()-1;
while(true)
{
int pos=partion(nums,left,right);
if(pos==k-1)   return nums[pos];
if(pos<k-1)   left=pos+1;
else right=pos-1;
}

}

int partion(vector<int> &nums,int begin,int end)
{
int left=begin+1;
int right=end;
while(left<=right)
{
if(nums[left]<nums[begin]&&nums[right]>nums[begin])
swap(nums[left],nums[right]);
if(nums[left]>=nums[begin]) left++;
if(nums[right]<=nums[begin]) right--;
}
swap(nums[begin],nums[right]);
return right;
}

#### leetcode 215: Kth Largest Element in an Array

2015-05-29 08:47:21

#### LeetCode 215:Kth Largest Element in an Array

2015-05-27 00:11:33

#### LeetCode OJ 215. Kth Largest Element in an Array 堆排序求解

2016-02-23 14:00:40

#### [leetcode] 215. Kth Largest Element in an Array 解题报告

2016-02-21 07:29:34

#### 【LeetCode-面试算法经典-Java实现】【215-Kth Largest Element in an Array（数组中第K大的数）】

2015-08-28 06:57:17

#### 【LEETCODE】215-Kth Largest Element in an Array

2015-12-10 19:31:21

#### LeetCode215. Kth Largest Element in an Array分治法

2016-10-12 11:50:27

#### leetcode 215 Kth Largest Element in an Array C++

2016-12-05 15:54:02

#### [LeetCode]215 数组第k大的数

2016-03-04 00:18:03

#### [LeetCode 215]Kth Largest Element in an Array （分治法/快速排序）

2016-09-14 21:07:59