其他分享
首页 > 其他分享> > 4. Median of Two Sorted Arrays

4. Median of Two Sorted Arrays

作者:互联网

This problem can be solved by using two PriorityQueue(s), which is just the same solution as 295. Find Median from Data Stream.

    PriorityQueue<Integer> smallQ = new PriorityQueue<>((x, y) -> y - x);
    PriorityQueue<Integer> largeQ = new PriorityQueue<>();
    int count = 0;

    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        addToQueue(nums1, smallQ, largeQ);
        addToQueue(nums2, smallQ, largeQ);
        if (count % 2 == 0) {
            int a = smallQ.poll();
            int b = largeQ.poll();
            return (double) ((a + b) / 2.0);
        } else {
            return smallQ.poll();
        }
    }

    private void addToQueue(int[] nums, PriorityQueue<Integer> smallQ, PriorityQueue<Integer> largeQ) {
        for (int i = 0; i < nums.length; i++) {
            if (count % 2 == 1) {
                smallQ.offer(nums[i]);
                largeQ.offer(smallQ.poll());
            } else {
                largeQ.offer(nums[i]);
                smallQ.offer(largeQ.poll());
            }
            count++;
        }
    }

 

标签:smallQ,offer,Arrays,Median,PriorityQueue,int,Sorted,poll,largeQ
来源: https://www.cnblogs.com/feiflytech/p/15934291.html