原题目:
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.
解析:题目要求找出数组中第k大的数。可以使用分治算法,在数组中随机取一个数r,将数组分为值大于r、值等于r、值小于r的三部分,分别记作vh,v,vl。则:若k<=|vh|,findKthLargest(nums,k)=findKthLargest(vh,k);若|vh|<k<=|vh|+|v|,return r;若k>|vh|+|v|,findKthLargest(nums,k)=findKthLargest(vl,k-|vh|-|v|),搜索范围迅速缩减,算法复杂度为O(n)。
#include <ctime>
#include <cstdlib>
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
vector<int> vl, v, vh;
srand(time(0));
int n = rand() % nums.size();
for(int i=0; i<nums.size(); i++)
{
if(nums[i] > nums[n]) vh.push_back(nums[i]);
else if(nums[i] == nums[n]) v.push_back(nums[i]);
else vl.push_back(nums[i]);
}
if(k > vh.size() && k <=vh.size()+v.size()) return nums[n];
else if(k <= vh.size()) return findKthLargest(vh, k);
else return findKthLargest(vl, k-vh.size()-v.size());
}
};