Find the kth largest element in an unsorted array. Note that it was the kth largest element in the sorted order and not the kth distinct element.
For example,
Given [3,2,1,5,6,4]
k = 2
and, return 5
.
Note:
You may assume k are always valid, 1≤k≤array ' s length.
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
Method One: Sort O (nlogn) using STL
int findKthLargest(vector<int>int k) { sort(nums.begin(),nums.end()); return nums[nums.size()-k];}
Law two: Write your own quick sort O (nlogn)
intFindkthlargest ( vector<int>& Nums,intk) {QuickSort (nums,0, Nums.size ());returnNums[nums.size ()-K];}voidQuickSort ( vector<int>&nums,intLeftintright) {inti = left, j = right-1;if(I < J) {intPO = nums[i]; while(I < J) { while(I < J && Nums[j] >= po) j--;if(I < J) {nums[i++] = nums[j]; } while(I < J && Nums[i] <= po) i++;if(I < J) {nums[j--] = nums[i]; }} Nums[i] = PO; QuickSort (Nums, left, i); QuickSort (Nums, i+1, right); }}
Method Three: Using the construction method time complexity O (KLOGN)
int findKthLargest(vector<int>int k){ make_heap(nums.begin(), nums.end()); for(auto i=0; i<k-1;i++){ pop_heap(nums.begin(), nums.end()); nums.pop_back(); } return nums.front();}
Method Four: This method is seen by the Forum, O (N)
intFindkthlargest ( vector<int>& Nums,intK) {intI, M, N, pivot, head =0, tail = nums.size ()-1, MAXV; while(1) {m = head, n= tail; Pivot = nums[m++]; while(M <= N) {if(Nums[m] >= pivot) m++;Else if(Nums[n] < pivot) n--;Else{Swap (nums[m++], nums[n--]); } }if(M-head = = k)returnPivotElse if(M-head < k) {k-= (m-head); head = m; }Else{tail = m1; Head = head+1; } }}
Leetcode[215]-kth largest Element in an Array