4. Median of Two Sorted Arrays
来源:互联网 发布:centos查看php版本 编辑:程序博客网 时间:2024/05/20 22:30
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
Example 1:
nums1 = [1, 3]nums2 = [2]The median is 2.0
Example 2:
nums1 = [1, 2]nums2 = [3, 4]The median is (2 + 3)/2 = 2.5
Solution:
Tips:
transform it to find the Nth minimum or maximum question in two sorted arrays.
Java Code:
public class Solution { public double findMedianSortedArrays(int[] nums1, int[] nums2) { int l1 = nums1.length; int l2 = nums2.length; if ((l1 + l2) % 2 == 0) { int left = findTheNthMinimumNumber(nums1, 0, l1 - 1, nums2, 0, l2 - 1, (l1 + l2) / 2); int right = findTheNthMinimumNumber(nums1, 0, l1 - 1, nums2, 0, l2 - 1, (l1 + l2) / 2 + 1); return (left + right) / 2.0; } return findTheNthMinimumNumber(nums1, 0, l1 - 1, nums2, 0, l2 - 1, (l1 + l2) / 2 + 1); } public int findTheNthMinimumNumber(int[] a1, int b1, int e1, int[] a2, int b2, int e2, int k) { int l1 = e1 - b1 + 1; int l2 = e2 - b2 + 1; if (l1 < l2) { return findTheNthMinimumNumber(a2, b2, e2, a1, b1, e1, k); } if (l1 == 0) { return a2[k - 1]; } if (l2 == 0) { return a1[k - 1]; } if (k == 1) { return a1[b1] > a2[b2] ? a2[b2] : a1[b1]; } int i2 = (b2 + k / 2 - 1) > e2 ? e2 : (b2 + k / 2 - 1); int i1 = b1 + k - (i2 - b2 + 1) - 1; if (a1[i1] == a2[i2]) { return a1[i1]; } if (a1[i1] < a2[i2]) { return findTheNthMinimumNumber(a1, i1 + 1, e1, a2, b2, i2, i2 - b2 + 1); } return findTheNthMinimumNumber(a1, b1, i1, a2, i2 + 1, e2, i1 - b1 + 1); }}
0 0
- [LeetCode]4.Median of Two Sorted Arrays
- LeetCode 4. Median of Two Sorted Arrays
- LeetCode --- 4. Median of Two Sorted Arrays
- [Leetcode] 4. Median of Two Sorted Arrays
- 4.Median of Two Sorted Arrays
- [LeetCode]4.Median of Two Sorted Arrays
- 4. Median of Two Sorted Arrays
- 4.Median of Two Sorted Arrays
- 4. Median of Two Sorted Arrays
- 4. Median of Two Sorted Arrays
- 【leetcode】4. Median of Two Sorted Arrays
- Leetcode-4.Median of Two Sorted Arrays
- 4. Median of Two Sorted Arrays
- 4. Median of Two Sorted Arrays
- LeetCode-4.Median of Two Sorted Arrays
- leetcoode 4. Median of Two Sorted Arrays
- Leetcode 4. Median of Two Sorted Arrays
- leetcode 4. Median of Two Sorted Arrays
- JAVA输入输出流(IO)
- Short-Time Fourier Transform
- SXOI2016 部分解题报告
- Java与C++的差异(1)
- 异常处理——异常函数之SetUnhandledExceptionFilter(子进程处理)(3)
- 4. Median of Two Sorted Arrays
- 5-13 是否完全二叉搜索树 (30分)
- coder初入职场必备:Eclipse+Tomcat8+MAVEN+SVN 工作环境搭建
- Android Device Monitor 文件管理的常见问题
- Canvas学习
- java观察者模式不一样的使用
- Java知识点小总结(一)
- Service和IntentService与Acticity之间的通信
- nyistOJ-石子合并(一)(区间DP)