- Kth Largest Element in an Array
Medium
1933
161
Favorite
Share
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.
Example 1:
Input: [3,2,1,5,6,4] and k = 2
Output: 5
Example 2:
Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4
题意:在一个无序数组中找第k大的数。
解法1:利用快速排序的思想,选取一个关键字,然后进行一趟排序,最后看这个关键字的位置,如果我们最后需要的答案在右边那么只需要进行右边的查找,同理,如果只需要查找左边,那么只查找左边即可。
代码:
/*
二分的做法
*/
class Solution
{
public:
int quickSort(vector<int> &nums, int left, int right)
{
int low,high;
low = left, high = right;
int privo_key = nums[low];
while(low < high)
{
while(low < high && nums[high] >= privo_key) --high;
nums[low] = nums[high];
while(low < high && nums[low] <= privo_key) ++low;
nums[high] = nums[low];
}
nums[low] = privo_key;
return low;
}
int findKthLargest(vector<int>& nums, int k)
{
int ans_index = nums.size() - k;
int index = -1;
int l = 0;
int r = nums.size() - 1;
while(ans_index != index)
{
index = quickSort(nums, l, r);
if(index < ans_index) l = index + 1;
else r = index -1;
}
return nums[ans_index];
}
};
法2: 那就是使用一个大小为k的优先队列,时间复杂度为O(nlogk)
代码:
/*
优先队列的做法,时间复杂度为O(nlogk)
*/
class Solution
{
public:
int findKthLargest(vector<int>& nums, int k)
{
priority<int, vector<int>, greater<int>> Q;
int len = nums.size();
for(int i = 0; i < len; i++)
{
if(Q.size() < k) Q.push(nums[i]);
else
{
int top = Q.top();
if(top < nums[i])
{
Q.pop();
Q.push(nums[i]);
}
}
}
return Q.top();
}
};