File tree Expand file tree Collapse file tree 1 file changed +84
-0
lines changed Expand file tree Collapse file tree 1 file changed +84
-0
lines changed Original file line number Diff line number Diff line change 1+ ### [ Back2Home] ( https://github.com/CodingWallah/ArraysCodingQuestions/main/README.md )  | [ Go2Video] ( # )  
2+ 
3+ 1 )  min heap = uses for largest ?
4+ 
5+ 2 )  max heap = uses for smallest ?
6+ 
7+ ### WHEN max and when min HEAPS and WHY ?  
8+ 
9+  Note- k is small = min; | k is large = MAX;
10+ ``` java 
11+ 
12+ // sol1 = using sorting or trick
13+ //  Time complexity = O(NlogN)
14+ class  Solution  {
15+  public  int  findKthLargest (int [] nums , int  k ) {
16+  Arrays . sort(nums);
17+  return  nums[nums. length- k];
18+  }
19+ }
20+ 
21+ ``` 
22+ 
23+ ``` java 
24+ 
25+ // MIN HEAP APPROACH = Best Solution O(N + NlogK) time complexity
26+ PriorityQueue<Integer >  minheap =  new  PriorityQueue<Integer > ();
27+  for (int  i= 0 ;i< k;i++ )
28+  minheap. add(nums[i]);
29+  
30+  
31+  for (int  i= k;i< nums. length;i++ ){
32+  if (nums[i]> minheap. peek()){
33+  minheap. poll();
34+  minheap. add(nums[i]);
35+  }
36+  }
37+ return  minheap. peek();
38+ ``` 
39+ ``` java 
40+ 
41+ // MIN HEAP EASY & CONCISE IMPLEMENTATION
42+ PriorityQueue<Integer >  pq =  new  PriorityQueue<Integer > (); 
43+  for (int  i :  nums){
44+  pq. add(i);
45+  if (pq. size()> k){
46+  pq. remove();
47+  }
48+  }
49+  
50+  return  pq. remove();
51+ 
52+ ``` 
53+ 
54+ 
55+ ``` java 
56+ // MAX HEAP APPROACH = Best Solution O(N + NlogK) time complexity
57+ PriorityQueue<Integer >  maxHeap =  new  PriorityQueue<Integer > (Collections . reverseOrder()); 
58+  for (int  i= 0 ;i< nums. length- k+ 1 ;i++ )
59+  maxHeap. add(nums[i]);
60+  
61+  for (int  i= nums. length- k+ 1 ;i< nums. length;i++ ){
62+  if (nums[i]< maxHeap. peek()){
63+  maxHeap. poll();
64+  maxHeap. add(nums[i]);
65+  }
66+  }
67+ 
68+  return  maxHeap. peek(); 
69+  }
70+  
71+ ``` 
72+ 
73+ ``` java 
74+ // MAX HEAP EASY & CONCISE IMPLEMENTATION
75+ PriorityQueue<Integer >  pq =  new  PriorityQueue<Integer > (Collections . reverseOrder()); 
76+  for (int  i :  nums){
77+  pq. add(i);
78+  
79+  for (int  i= 1 ;i< k;i++ )
80+  pq. poll();
81+  
82+  return  pq. peek(); 
83+  
84+ ```
                         You can’t perform that action at this time. 
           
                  
0 commit comments