Can use a Priority Queue in Java too.


  • 0
    S
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
            
            int len = nums1.length + nums2.length;
            int count = len/2 + 1;
            
            PriorityQueue<Integer> queue = new PriorityQueue<Integer>(count);
            for(int i : nums1)
            {
                queue.add(i);
                if(queue.size() > count) 
                    queue.poll();
            }
            for(int i : nums2)
            {
                queue.add(i);
                if(queue.size() > count) 
                    queue.poll();
            }
            
            if(len % 2 != 0) 
                return queue.peek();
            else
            {
                int a = queue.poll();
                int b = queue.poll();
                return ((double)a + (double)b)/2;
            }
        }
    

  • 0
    K

    @sandhyas I used the same logic and my solution was accepted too but I am a bit confused about the complexity of the solution. I think the complexity is O((m+n)/2), weird it got accepted.


Log in to reply
 

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