K-Large elements

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.