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
Back: 2 opportunistic energy through:
1 classFinder {2 Public:3 intFindkth (vector<int> A,intNintK) {4 //Write code here5 sort (A.begin (), A.end ());6 returnA[n-K];7 }8};
With the idea of quick-line:
1#include <iostream>2#include <vector>3#include <string>4#include <queue>5#include <stack>6#include <unordered_map>7#include <map>8#include <algorithm>9 using namespacestd;Ten One //Use the idea of a quick line: for example, to find the 24th-largest element within 49 elements, follow these steps: A //1. Make a quick row (put large elements in the first half, small elements in the second half), assuming that the resulting middle axis is P - //2. Judge P-low = = K-1, if set up, direct output A[P], (because the first half of the k-1 is greater than the a[p] element, so a[p] for the K-large Element) - //3. If P-low > K-1, then the element k is in the first half, at this time, update high = p-1, proceed to step 1 the //4. If P-low < k-1, then the element of the K-large is in the second half, at which time the low = P + 1 is updated, and k = k-(P-low + 1), proceed to step 1. - //The actual complexity is not O (NLGN), but O (n), because the general order is to get a whole ordered array, and this method can remove the "half" element at a time. - classFinder { - Public: + intPartation (vector<int>& A,intLowintHigh ) { - intKey =A[low]; + while(Low <High ) { A while(Low < High && A[high] <=key) athigh--; -A[low] =A[high]; - while(Low < High && A[low] >=key) -low++; -A[high] =A[low]; - } inA[low] =key; - returnLow ; to } + intFindkth (vector<int>& A,intLowintHighintk) - { the intPart =Partation (A, low, high); * if(k = = Part-low +1) $ returnA[part];Panax Notoginseng Else if(k > Part-low +1) - returnFindkth (A, part +1, high, K-part + low-1); the Else + returnFindkth (A, low, part-1, k); A the } + intFindkth (vector<int> A,intNintK) { - //Write code here $ returnFindkth (A,0N1, K); $ } - }; - the - //TestWuyi intMain () the { -vector<int> v{1,3,5,2,2 }; Wu Finder solution; -Cout<<solution.findkth (V,5,3); About}
Search for the K-Big NetEase 2016 internship research and development engineer programming problem