File tree Expand file tree Collapse file tree 2 files changed +30
-0
lines changed Expand file tree Collapse file tree 2 files changed +30
-0
lines changed Original file line number Diff line number Diff line change 1+ import  Heap 
2+ 
3+ def  findKthLargestElement (nums :list ,k :int ):
4+     ''' 
5+     The problem here is to find the Kth Largest Element from the array. 
6+     to solve this we could've used sort and given the answer but it would've cost us O(N*logN) where N is the number of elements in the array 
7+ 
8+     to even optimize that solution we can use heaps. 
9+     the idea here is: 
10+     1. create a min-heap with adding all the values as negative to it 
11+     2. deleting till second last step 
12+     3. returning the element at the last step as the answer 
13+ 
14+     T - O(N +K*log(N)) where K is the position of Kth largest element and N is the number of elements in the array 
15+ 
16+     ''' 
17+     h = Heap .BinaryHeap ()
18+     [h .insert (- num ) for  num  in  nums ]
19+     [h .delete () for  _  in  range (k - 1 )]
20+ 
21+     return  - h .delete ()
22+ 
23+ 
24+ if  __name__  ==  '__main__' :
25+     
26+     nums = [2 ,3 ,5 ,6 ,4 ]
27+     k = 2 
28+     kthLargestElement  =  findKthLargestElement (nums ,k )
29+ 
30+     print ("the Kth(" + str (k )+ ") largest element is" ,kthLargestElement )
 
 
   
 
     
   
   
          
    
    
     
    
      
     
     
    You can’t perform that action at this time.
  
 
    
  
    
      
        
     
       
      
     
   
 
    
    
  
 
  
 
     
    
0 commit comments