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的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-22[开源]10.3K+ Star!轻量强大的开源运维平台,超赞!
- 2024-11-21Flutter基础教程:新手入门指南
- 2024-11-21Flutter跨平台教程:新手入门详解
- 2024-11-21Flutter跨平台教程:新手入门与实践指南
- 2024-11-21Flutter列表组件教程:初学者指南
- 2024-11-21Flutter列表组件教程:新手入门指南
- 2024-11-21Flutter入门教程:初学者必看指南
- 2024-11-21Flutter入门教程:从零开始的Flutter开发指南
- 2024-11-21Flutter升级教程:新手必读的升级指南
- 2024-11-21Flutter升级教程:轻松掌握Flutter版本更新