The problem of the KTH large number and the detailed solution of the algorithm outline are discussed

  • 2020-04-01 23:42:16
  • OfStack

Method 1: We can sort this random number group first from large to small, and then take out the first k is large, the total time complexity is O(n*logn + k).

Method 2: Using selection sort or interactive sort, the KTH largest number can be obtained after K times of selection. The total time complexity is order n times k.

Solution 3: using the idea of quicksort, find a random element X from the array S and divide the array into two parts, Sa and Sb. The element in Sa is greater than or equal to X, and the element in Sb is less than X. There are two situations:
1. If the number of elements in Sa is less than k, the k-|Sa| element in Sb is the k- largest number;
2. If the number of elements in Sa is greater than or equal to k, the KTH largest number in Sa is returned. The time complexity is approximately O(n).

Method 4: Binary [Smin,Smax] search result X, statistical X appears in the array, and the number greater than X in the array is k-1 is the KTH largest number. The average time complexity is order n times logn.

Method 5: Use O(4*n) method to the original number to form the maximum heap, and then pop out k times. O times 4 times n plus k times logn.

Method 6: Maintain a minimum heap of size k. Determine the size of the heap top for each element in the array. If the heap top is large, ignore it. Order n times logk.

Method 7: Hash is used to store the number of occurrences of element Si in the array. With the idea of counting sort, in the linear scanning process from large to small, the number with k-1 in front is the KTH largest number. On average, the time complexity is O(n).

 


Related articles: