Using MaxHeap- Runs in 157 ms. Can this be optimized ?


  • 0
    P
    public class Solution {
        public double findMedianSortedArrays(int[] nums1, int[] nums2) {
            PriorityQueue<Integer> maxHeap = new PriorityQueue<>((a,b)->b-a);
           for(int i=0;i<nums1.length;i++){
               maxHeap.add(nums1[i]);
           } 
           for(int i=0;i<nums2.length;i++){
               maxHeap.add(nums2[i]);
           }
           int m=maxHeap.size();
           if(m==1){
               return maxHeap.poll();
           }
           int i=1;
           double median = 0;
           if(m%2!=0) {
               while(i<=m/2+1) {
               if(i==m/2+1) {
                   median=maxHeap.poll();
               }else{
                    maxHeap.poll();
               }
               i++;
               }
               return (median);
               }
           else {
               while(i<=m/2+1) {
                   if(i==m/2 || i ==m/2+1) {
                       median+=maxHeap.poll();
                   }else {
                   maxHeap.poll();
                   }
                   i++;
               }
               return (median/2);
           }
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.