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++;
        }
    }

 

posted on 2022-02-25 03:41  阳光明媚的菲越  阅读(13)  评论(0编辑  收藏  举报