美文网首页
Lint 5. ** Kth Largest Element (

Lint 5. ** Kth Largest Element (

作者: Mree111 | 来源:发表于2019-10-08 23:21 被阅读0次

    Description

    Find K-th largest element in an array.

    Solution

    Quick selection O(N)

    class Solution:
       """
       @param n: An integer
       @param nums: An array
       @return: the Kth largest element
       """
       def quick_s(self,num,left,right,k):
           if left==right:
               return num[left]
           i=left
           j=right
           pivot = num[(i+j)//2]
           while i<=j:
               while i<=j and num[i]>pivot :
                   i+=1
               while i<=j and num[j]<pivot:
                   j-=1
               if(i<=j):
                   tmp = num[i]
                   num[i] = num[j]
                   num[j] = tmp
                   i+=1
                   j-=1
           if left + k-1 <= j:
               return self.quick_s(num,left,j,k)
           elif left + k -1 >= i:
               return self.quick_s(num,i,right,k-(i-left))
           else:
               return num[j+1]
       def kthLargestElement(self, n, nums):
           # write your code here
           return self.quick_s(nums,0,len(nums)-1,n)
    

    相关文章

      网友评论

          本文标题:Lint 5. ** Kth Largest Element (

          本文链接:https://www.haomeiwen.com/subject/lnoipctx.html