Tencent 35-Kth largest element in the array

Tencent 35-the Kth largest element in the array

Find the k-th largest element in the unsorted array. Note that what you need to find is the k-th largest element after the array is sorted, not the k-th different element.

Example 1:

Input: [3,2,1,5,6,4] and k = 2
Output: 5

You must be able to use the fast partition function. The
next step is to write the partition function correctly.
Python writes 8 lines of the partition function. Among them, lines 1, 2, 7, 8 are easy to remember. The
first line, pivot takes the first element value left,
In the second line, the moving j also starts from the left (guarantee that nums [j] itself must be less than or equal to pivot, and the initial is equal to)
. The third line pays attention to the range, i starts from left + 1, because the point of pivot does not need to be compared with itself
Note on line 4 that nums [i] and pivot are compared, the equal sign is not involved, nums [i] is less than pivot and there is an operation, nums [i] moves forward, and forward is related to j. The
fifth line is the most important because nums [j] It must be less than or equal to pivot (the initial value of nums [j] also proves this), so there is no need to directly exchange nums [j] and nums [i], and nums [j + 1] is not necessarily, nums [j +1] can be greater than or equal to pivot, and there must be, if nums [j +1] <pivot, j + 1 = i, then exchange nums [j +1] and nums [i] , If nums [j +1]> pivot, it is more reasonable to exchange nums [j +1] and nums [i]. In summary, it can be understood why the fifth step has j = j + 1 The
sixth line completes the exchange of nums [j] and nums [i] (At this time j is already added by 1) The
seventh line moves the initial left and move The exchange position of j (also verifies that nums [j] above must be less than or equal to pivot, and nums [j + 1] is not necessarily)
returns j, the index of pivot

class Solution:
    def partition(self,nums,left,right):
        pivot=nums[left]
        nums[left],nums[right]=nums[right],nums[left]
        store_index=left
        for i in range(left,right+1):
            if nums[i]<pivot:
                nums[store_index],nums[i]=nums[i],nums[store_index]
                store_index+=1
        nums[store_index],nums[right]=nums[right],nums[store_index]
        return store_index
    
    def findKthLargest(self, nums: List[int], k: int) -> int:
        ture_k=len(nums)-k
        left,right=0,len(nums)-1
        while(True):
            tmp=self.partition(nums,left,right)
            if tmp==ture_k:return nums[tmp]
            elif tmp<ture_k:left=tmp+1
            else:right=tmp-1
Published 93 original articles · praised 8 · 10,000+ views

Guess you like

Origin blog.csdn.net/zlb872551601/article/details/103649781