Finds the largest element in an unordered array of the first K. Note that you need to look for the first K-largest element after the array is sorted, not the K-different element.
Example 1:
[3,2,1,5,6,4] 和
K = 2 Output: 5
Example 2:
[3,2,3,1,2,4,5,5,6] 和
k = 4 Output: 4
Description
You can assume that K is always valid and 1≤k≤ the length of the array.
The most brutal way is to sort all the data, then take out the number of K, but do a lot of unnecessary sorting;
Here with the quick sort, and the idea of two points to find the K-Big data;
With the first number pivot, find the position of the number in the ordered sequence, if the position of the number on the left of K, on the right of the number to continue to find, if the number on the right of K, on the left of the number to continue to find
1 classSolution {2 Public:3 intPartition (vector<int>& num,intLowintHigh ) {4 intPivot =Num[low];5 while(low<High ) {6 while(LowHigh ;7 swap (Num[low], Num[high]);8 while(LowLow ;9 swap (Num[low], Num[high]);Ten } One returnLow ; A } - intFindkthlargest (vector<int>& Nums,intk) { - intL=0, R=nums.size ()-1; the while(true){ - intpos=partition (Nums, L, R); - if(pos>k-1) r=pos-1; - if(pos<k-1) l=pos+1; + if(pos==k-1)returnnums[k-1]; - } + } A};
You can also use the heap sort to find, heap sort is not very familiar, and then do
215. K largest element in an array