LeetCode – Median of Two Sorted Arrays Java
来源:互联网 发布:用 sql语句查询两张表 编辑:程序博客网 时间:2024/06/07 23:40
LeetCode Problem:
There are two sorted arrays A and B 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)).
Keys to solve this problem
This problem can be converted to the problem of finding kth element, k is (A’s length + B’ Length)/2.
If any of the two arrays is empty, then the kth element is the non-empty array’s kth element.
If k == 0, the kth element is the first element of A or B.
For normal cases(all other cases), we need to move the pointer at the pace of half of an array length.
public static double findMedianSortedArrays(int A[], int B[]) {int m = A.length;int n = B.length; if ((m + n) % 2 != 0) // oddreturn (double) findKth(A, B, (m + n) / 2, 0, m - 1, 0, n - 1);else { // evenreturn (findKth(A, B, (m + n) / 2, 0, m - 1, 0, n - 1) + findKth(A, B, (m + n) / 2 - 1, 0, m - 1, 0, n - 1)) * 0.5;}} public static int findKth(int A[], int B[], int k, int aStart, int aEnd, int bStart, int bEnd) { int aLen = aEnd - aStart + 1;int bLen = bEnd - bStart + 1; // Handle special casesif (aLen == 0)return B[bStart + k];if (bLen == 0)return A[aStart + k];if (k == 0)return A[aStart] < B[bStart] ? A[aStart] : B[bStart]; int aMid = aLen * k / (aLen + bLen); // a's middle countint bMid = k - aMid - 1; // b's middle count // make aMid and bMid to be array indexaMid = aMid + aStart;bMid = bMid + bStart; if (A[aMid] > B[bMid]) {k = k - (bMid - bStart + 1);aEnd = aMid;bStart = bMid + 1;} else {k = k - (aMid - aStart + 1);bEnd = bMid;aStart = aMid + 1;} return findKth(A, B, k, aStart, aEnd, bStart, bEnd);}
0 0
- [Leetcode] Median of Two Sorted Arrays (Java)
- [LeetCode][Java] Median of Two Sorted Arrays
- Median of Two Sorted Arrays --leetcode java
- LeetCode : Median of Two Sorted Arrays [java]
- leetcode:Median of Two Sorted Arrays 【Java】
- [LeetCode]Median of Two Sorted Arrays(Java)
- leetcode Median of Two Sorted Arrays(Java)
- Leetcode-Median of Two Sorted Arrays (java)
- LeetCode – Median of Two Sorted Arrays Java
- [leetcode NO.2] Median of Two Sorted Arrays (JAVA)
- leetcode第四题:Median of Two Sorted Arrays (java)
- 【leetcode with java】4 Median of Two Sorted Arrays
- Leetcode 4 Median of Two Sorted Arrays Java
- leetcode 004 Median of Two Sorted Arrays(java)
- LeetCode(java)4. Median of Two Sorted Arrays
- [LeetCode][4]Median of Two Sorted Arrays解析 -Java实现
- leetcode: 4. Median of Two Sorted Arrays (java)
- Leetcode 第四题< Median of Two Sorted Arrays>(Java)
- 为什么我们不要.NET程序员
- Android自动化测试之MonkeyRunner
- 配置PL/SQL 及 出现中文乱码的解决方法
- Pro Android学习笔记(八五):了解Package(4):lib项目
- windows窗口分析,父窗口,子窗口,所有者窗口
- LeetCode – Median of Two Sorted Arrays Java
- push页面后隐藏tabbar,pop后显示tabbar
- Nginx做正向代理并缓存文件
- 省选训练赛第4场D题(多米诺骨牌)
- 搜索引擎常见语法
- 很好,很强大 GDI+ 资料
- 【蓝桥杯练习系统】基础练习 闰年判断
- c++中 char 与typedef unsigned char byte区别
- Hash