Disorderly array to find a large number of k

Class fast algorithm row

Because only required to find the k-th largest number, no need to array all values ​​are sorted.

Fast row partition algorithm returns cnt key position in the array (an offset from the left), if cnt exactly equal to k, then the problem is solved; If cnt is less than k, go to the left to find the k; If cnt> k, then go to the right to find the first k-cnt months. Until the key position is equal to k-1, it is to find a solution to the problem.

/ * Partitioning algorithm fast row * / 
int Partition ( int * INPUT, int Low, int High)
 {
    int tmp = INPUT [Low]; // get a reference element

    while (low < high) {
        while (low < high && input[high] >= tmp) {
            high--;
        }
        input[low] = input[high];

        while (low < high && input[low] <= tmp) {
            low++;
        }
        input[high] = input[low];
    }

    input[low] = tmp;
    return low;
}

// obtained here is the k small, the conversion to their nk 
int findK ( int * Array, int left, int right, int k) {
     // ( "% D% D% D \ n-", the printf left, right, K); 
    int I = Partition (Array, left, right);
     int CNT = I - + left . 1 ;
     IF (K == CNT) {
         return Array [I];
    } else if (k < cnt) {
        return findK(array, left, i - 1, k);
    } else if (k > cnt) {
        return findK(array, i + 1, right, k-cnt);
    }
    return 0;
}

The time complexity of this solution is O (N * lgK), logK times for O (N), than sorting Solution

The minimum heap Solution

We construct a minimum size k of the stack, the stack root to a minimum value. If the array were some of the largest number in the heap solution, then the value is the root of the problem of the heap.

STL may be implemented in the priority queue, because the internal heap priority queue is the maximum / minimum heap achieved.

Solution of this time complexity of O (NlogK), N times logK. However, compared with the class of fast sorting algorithm, the need for additional storage space.

 

 

Reference links:

1. https://www.jianshu.com/p/33ee33ce8699

2. https://blog.csdn.net/qq_14821023/article/details/50793468

Guess you like

Origin www.cnblogs.com/lfri/p/12526994.html