4. Median of Two Sorted Arrays

2022/2/25 6:21:40

本文主要是介绍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++;
        }
    }

 



这篇关于4. Median of Two Sorted Arrays的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程