To solve this problem, we are following the min Heap approach. We will be using Priority Queue for that.
A brief about Priority Queue:
A PriorityQueue is what is called a binary heap. It is only ordered/sorted in the sense that the first element is the least. In other word, it only cares about what is in the front of the queue, the rest are “ordered” when needed. Therefore, whenever an element is added, it internally heapifies and stores them as per the Comparator function mentioned. By default, it is in ascending order.
Hence the algorithm is as follows:
Here is the full code:
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
for(int i=0;i<m;i++){
minHeap.add(nums1[i]);
}
for(int i=0;i<n;i++){
minHeap.add(nums2[i]);
}
while(!minHeap.isEmpty()){
for(int i=0;i<m+n;i++){
nums1[i]=minHeap.remove().intValue();
}
}
}
}
When in doubt, work it out! Happy coding! :)
#java #algorithms #leetcode #coding-interviews #arrays