Merge two binary Max heaps Geeks For Geeks
Problem Link:
https://practice.geeksforgeeks.org/problems/merge-two-binary-max-heap0144/1#
It is also the problem of the day for
Solution:
class Solution{
public int[] mergeHeaps(int[] a, int[] b, int n, int m) {
PriorityQueue<Integer>pq=new PriorityQueue<Integer>(Collections.reverseOrder());
for(int i=0;i<a.length;i++){
pq.add(a[i]);
}
for(int j=0;j<b.length;j++){
pq.add(b[j]);
}
int arr[]=new int[pq.size()];
int index=0;
while(!pq.isEmpty()){
arr[index++]=pq.remove();
}
return arr;
}
}
TOTAL TEST CASES:10037
TIME COMPLEXITY:O(Max(N,M))[GFG Time: 1.4/3.4]
SPACE COMPLEXITY: O(1)
AUXILIARY SPACE: O(N+M)[Priority Queue Is Used]
APPROACH USED:
Here we will use the basic approach as we will add all the elements in the queue.
Priority queue will do automatically sort since we have to return the output as array sorted in descending order. So for that, we will use PriorityQueue(Collections.reverseOrder()).
"Thanks For Reading.😇"
"Share Further To Increase Knowledge Treasure.😊"
Comments
Post a Comment