Given an array a, it is required to find the number k in array a. There are a number of solutions to this problem, here I only give three kinds:
Method 1:
Sort the array a, and then iterate over it to find the K-large number. The time complexity of the method is O (N*LOGN)
Method 2:
Using the simple choice of sorting method of thought, each time by comparison to select the largest number to compare the K-time to find out the number of the K-large. The time complexity of the method is O (n*k), and the worst case is O (n^2).
Method 3:
This approach is the focus of this article, can take advantage of the idea of the fast line, the first time the fast row each execution can determine the final position of an element, if this position is n-k (where n is the length of array a), then it is equivalent to find the element K large. If M > n-k is large, then the number k will be
Between A[0]~a[m-1], if M < n-k, then the number of K-large must be between a[m+1]~a[n-1]. The entire process can be implemented recursively, with the following specific code:
#include <iostream> #include <cassert> #include <vector> #include <stack> #include <cstdio > #include <unordered_map> #include <queue> #include <cstring> #include <cstdlib> #include <cmath> #include <algorithm>using namespace Std;int Partition (int* arr,int Low, int.) {int temp = Arr[low ]; while (Low < high) {when (Low < high && Arr[high] >= temp) high--; Arr[low] = Arr[high]; while (Low < high && Arr[low] <= temp) low++; Arr[high] = Arr[low]; } Arr[low] = temp;//Determine the position of the reference element return low;} int kthelement (int * arr,int low, int high,int n, int k) {if (arr = = nullptr | | Low >= High | | k > N)//boundary conditions and special input places Manager return 0; int pos = Partition (Arr,low,high); while (pos! = n-k) {if (pos > n-k) {high = low-1; pos = Partition (Arr,low,high); } if (pos < n-k) { Low = pos + 1; pos = Partition (Arr,low,high); }} return Arr[pos];} int main () {int a[]={1,5,5,7,88,11}; Cout<<kthelement (a,0,5,6,2); }
Attention:
1. The number of K-large numbers in the array corresponds to the position of n-k (in ascending order).
2. The time complexity of the algorithm is generally O (N).
Look for the number of K in the array