Believe that the fast sorting algorithm this classic algorithm everyone is not unfamiliar. But based on the various variants of the fast algorithm, do you understand?
One of the most important variants is the fast selection algorithm, which is often used to look for elements of the K-small/K-size in an unordered array. Fast selection and its variants are the most efficient selection algorithms used in practical applications.
The general idea of quick selection is consistent with the quick sort, selecting an element as a datum to partition the elements, dividing the elements less than and greater than the datum into two regions on the left and right sides of the datum. The difference is that the fast choice does not recursively access the bilateral, but instead continues to look for elements that are only recursive into one side. This reduces the average time complexity, from O (n log n) to O (n), although the worst case is still O (n2).
LC on a topic:
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.
The following solution comments in detail, can well understand the fast selection algorithm, this can be used as a template to write down. Can AC be not wrong at an interview? It's not that easy, actually. The key to remembering is a deep understanding.
classSolution {/*** Solution 0. Heap O (KLOGN) * Solution 1. Quick selection: O (n)*/ Public intFindkthlargest (int[] Nums,intk) {if(Nums.length = = 0 | | nums = =NULL)return0; intleft = 0, right = nums.length-1; while(true) { intPosition =partition (Nums, left, right); if(Position = = k-1)returnNums[position];//each round returns to the final position of the current pivot, and its position is the number of the first, if it is just the K-large Else if(Position > K-1) right = position-1;//the idea of two points Elseleft = position + 1; } } Private intPartitionint[] Nums,intLeftintRight ) { intPivot =Left ; intL = left + 1;//Remember here L is left + 1 intR =Right ; while(L <=r) { while(l <= R && Nums[l] >= Nums[pivot]) l++;//find the first number less than Nums[pivot] from the left while(l <= R && Nums[r] <= Nums[pivot]) r--;//find the first number greater than nums[pivot] from the right if(l <= R && Nums[l] < Nums[pivot] && Nums[r] >Nums[pivot]) {Swap (nums, L+ +, r--); }} swap (Nums, pivot, R); //swap pivot to the final position it belongs to, that is, the position of R, because at this point R is bigger than R and the right side is smaller than R returnR//returns the position of the final pivot } Private voidSwapint[] Nums,intLintr) {intTMP =Nums[l]; NUMS[L]=Nums[r]; NUMS[R]=tmp; } }
A fast selection algorithm of classical algorithm