Finds the largest element in an unordered array of the first K. Note that it is the nth largest element in an ordered array of arrays, not the K-different elements.
For example
Given [3,2,1,5,6,4] and k = 2, return 5.
Precautions:
You can assume that K is always valid, 1≤k≤ the length of the array.
See: https://leetcode.com/problems/kth-largest-element-in-an-array/description/
Method One:
Class Solution {public: int findkthlargest (vector<int>& nums, int k) { priority_queue<int,vector <int>,greater<int>> MinH; for (int i=0;i<nums.size (); ++i) { if (minh.size () <k) { minh.push (nums[i]); } else { if (Minh.top () <nums[i]) { minh.pop (); Minh.push (Nums[i]); }} return Minh.top (); }};
Method Two:
Class Solution {public: 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--]); if (Nums[l] >= pivot) l++; if (Nums[r] <= pivot) r--; } Swap (Nums[left], nums[r]); return r; } 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;}} ;
Reference: https://www.cnblogs.com/grandyang/p/4539757.html
215 Kth largest element in a array of K largest elements