1、题目描述
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.
2、解题思路
题意:从一个无序数组中找出第k个最大值,然后输出
方法A:先进行排序,然后输出下标为k-1的元素。
方法B:使用分治的思想,任意选择一个元素作为基准,大于它的元素存入数组l,小于它的元素存入r,等于它的存入e,如果k不大于|l|,递归调用函数本身,在l中继续寻找第k大的元素;如果|l|
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
int left = 0, right = nums.size() - 1;
while (true) {
int pos = partition(nums, left, right);
if (pos == k - 1) return nums[pos];
if (pos > k - 1) right = pos - 1;
else left = pos + 1;
}
}
int partition(vector<int>& nums, int left, int right) {
int pivot = nums[left];
int l = left + 1, r = right;
while (l <= r) {
if (nums[l] < pivot && nums[r] > pivot)
swap(nums[l++], nums[r--]);//exchange of element
if (nums[l] >= pivot) l++;
if (nums[r] <= pivot) r--;
}
swap(nums[left], nums[r]);
return r;
}
};
B:
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
int v=nums[0];
vector<int> l,e,r;
int kth;
auto n=nums.size();
for(int i=0;i<n;i++){
int t=nums[i];
if (t>v) l.push_back(t);
else{
if(t==v) e.push_back(t);
else r.push_back(t);
}
}
int n1=l.size();
if (n1>=k) kth=findKthLargest(l,k);
else{
int n2=e.size();
if(n1<k<=n1+n2) kth=v;
else{
kth=findKthLargest(r,k-n1-n2);
}
}
return kth;
}
};