Transmission Door
There is an array of integers, please find out the number of K large in the array according to the idea of quick sorting.
Given an integer array a, given its size n and the K (k between 1 and N) to be found, return the number of K to ensure that the answer exists.
Test examples:
[1,3,5,2,2],5,3
Returns: 2
Note
Note When writing a quick line:
while (I < j) { while (J > I && a[j] > A[left]) j--; while (I < J && A[i] <= a[left]) i++; if (I < j) { swap (a[i],a[j]); } } while (J > I && a[j] > A[left]) j--; while (I < J && A[i] <= a[left]) i++; These two order can not be reversed, or the next bidding clubs dislocation of a
1 classFinder {2 Public:3 intFindkth (vector<int> A,intNintK) {4 //Write code here5 returnQuickfind (A,0N1, K);6 }7 8 intQuickfind (vector<int> &a,intLeftintRightintK) {9 inti = Left,j =Right ;Ten while(I <j) { One while(J > I && a[j] > A[left]) j--; A while(I < J && A[i] <= a[left]) i++; - if(I <j) { - swap (a[i],a[j]); the } - } - swap (a[left],a[i]); - intdis = right-i +1; + if(Dis = =K) { - returnA[i]; + } A Else if(K <dis) { at returnQuickfind (A,i +1, right,k); - } - Else{ - returnQuickfind (A,left,i-1Kdis); - } - } in};
--------------------------------------------------
Leetcode:
Transmission Door
215. Kth largest Element in an ArrayQuestionEditorial SolutionMy Submissions
- Total accepted:67793
- Total submissions:195182
- Difficulty:medium
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]
and k = 2, 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.
Subscribe to see which companies asked this question
Hide TagsHeap Divide and ConquerShow Similar Problems
1 classSolution {2 Public:3 intFindkthlargest (vector<int>& Nums,intk) {4 returnQuickfind (Nums,0, Nums.size ()-1, k);5 }6 7 intQuickfind (vector<int> &a,intLeftintRightintK) {8 inti = Left,j =Right ;9 while(I <j) {Ten while(J > I && a[j] > A[left]) j--; One while(I < J && A[i] <= a[left]) i++; A if(I <j) { - swap (a[i],a[j]); - } the } - swap (a[left],a[i]); - intdis = right-i +1; - if(Dis = =K) { + returnA[i]; - } + Else if(K <dis) { A returnQuickfind (A,i +1, right,k); at } - Else{ - returnQuickfind (A,left,i-1Kdis); - } - } -};
NetEase 2016 Internship research engineer [programming questions] looking for the K-large and Leetcode 215. Kth largest Element in an Array