Kth Largest Element in an Array
Kth Largest Element in an Array
Total Accepted: 32668 Total Submissions: 109273 Difficulty: Medium
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.
class Solution { private: int partion(vector<int>& nums,int start,int end){ if(end-start==1){ return start; } srand(time(0)); int rindex = start + rand()%(end-start); swap(nums[rindex],nums[end-1]); int i=start-1,j=start; while(j < end-1){ if(nums[j] < nums[end-1]){ swap(nums[++i],nums[j]); } ++j; } swap(nums[++i],nums[end-1]); return i; } public: int findKthLargest(vector<int>& nums, int k) { int start = 0; int end = nums.size(); k = end - k; int index = partion(nums,start,end); while(index != k){ if(index < k){ start = index+1; }else{ end = index; } index = partion(nums,start,end); } return nums.size()==0 ? 0 : nums[k]; } };
写者:zengzy
出处: http://www.cnblogs.com/zengzy
标题有【转】字样的文章从别的地方转过来的,否则为个人学习笔记