1. Topic Analysis:
Finding the number of K in an unordered array , the intuitive feeling is to first order and then find the element labeled K-1 , time complexity O (NLGN). Here, we want to explore the existence of time complexity < O (nlgn), and an efficient algorithm that is approximately equal to O (N) .
Do you remember the idea of our quick sequencing? The front and back parts are divided recursively by "partition". In this problem solving strategy, the division function based on the fast row can use the "attack method", continuously from the original interval [0,n-1] to the middle of the search for the number of K , about the direction of the search:
2. Reference code:
1#include <cstdio>2 3 #defineSwap (x, y) {int temp=x;x=y;y=temp;}4 5 using namespacestd;6 7 8 9 Const intmaxn=1e5;Ten One intA[MAXN]; A - - the intPartint*arr,intPintq) { - - inti=p-1; - + for(intj=p;j<q;j++)if(arr[j]<A[q]) { - +i++; A at swap (arr[i],arr[j]); - - } - -i=i+1; - in swap (arr[i],arr[q]); - to returni; + - } the * intFINDK (int*arr,intNintk) { $ Panax Notoginseng intp=0, q=n-1; - the while(p<q) { + A //int m=p+ (Q-P)/2; the + intf=Part (ARR,P,Q); - $ //printf ("f=%d\n", f); //For tested $ - if(f==k) { - the returnArr[k]; - Wuyi}Else if(f>k) { the -q=f-1; Wu -}Else{ About $p=f+1; - - } - A } + the returnARR[K];//needed - $ } the the intMain () { the the intn,k; - in /* the the *input includes 2 integers. n indicates the num of elements, About the *k means for the kth larger num to be found the the */ + - while(SCANF ("%d%d", &n,&k) = =2){ the Bayi for(intI=0; i<n;i++) scanf ("%d",&a[i]); the the intANS=FINDK (a,n,k-1); - -printf"%d\n", ans); the the } the the return 0; - the } the the /*94 the data for the test: the the 4 298 About 1 5433 2 - 101 4 3102 103 1 5433 2104 the 4 4106 107 1 5433 2108 109 */ the 111
3. Test results:
Conclusion:
The implementation of this algorithm only applies to the general situation, if k=1 or 2 Smart You should know not to apply the algorithm of this article, simple traversal Save the maximum, so that the specific problem has to be specific analysis ^_^
Quickly find the K-large number in an unordered array?