Title Description: Find the element of the K-large in the array
Example: Given an array [9,3,2,4,8], the third largest element is 4, given the array [1,2,3,4,5], the first large element is 5, the second largest element is 4, the third largest element is 3, and so on
And the title of the previous median (see: Click to open the link) is exactly the same, it should be noted that since the array to be sorted in ascending order, then the K-element is the inverse of the array K-bit, that is, the index is n-k element, or according to the idea of the fast line, through a split function to find each pivot should be Compare this position with the n-k, if it happens to be n-k, return directly, if it is less than n-k, then you need to find it in the array that follows the pivot, and if it is greater than n-k, you need to find it in the array in front of the pivot. If you have any questions about this idea, please go to the link I just gave.
So the code is almost the same as the "median" question, as follows:
Class Solution: # @param K & A A integer and an array # @return ans A integer def kthlargestelement (self, k, a): n = Len (A) if n = = 0:return None begin, End = 0, n-1 index = self.partition ( A, 0, n-1) while index! = n-k: If index > n-k: End = Index-1 in Dex = Self.partition (A, begin, end) Else:begin = index + 1 index = Self.partitio N (A, begin, end) return A[index] def partition (self, A, begin, end): If begin >= End:return begin pivot = a[begin] Index = begin for I in range (begin + 1, End + 1): if A[i] <= Pivot:index + 1 A[i], a[index] = A[index], a[i] A[begin], A[index] = A[index], A[begin] return index
These two questions, including the problem of color in front, are fast-track applications, so sometimes learning algorithms really needs to understand the rationale behind it, not just the code that writes the problem.
K-Large elements