[LeetCode] Median of Two Sorted Arrays
来源:互联网 发布:办公室网络安装 编辑:程序博客网 时间:2024/06/05 16:35
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)).
转换为求第K大的数
public double findMedianSortedArrays(int A[], int B[]) { if (A == null || B == null) { return 0; } if (A.length == 0 && B.length == 0) { return 0; } int m = A.length; int n = B.length; if (((m + n) & 1) == 1) { return getKthNum(A, B, 0, m - 1, 0, n - 1, (m + n) / 2 + 1); } else { return (getKthNum(A, B, 0, m - 1, 0, n - 1, (m + n) / 2 + 1) + getKthNum(A, B, 0, m - 1, 0, n - 1, (m + n) / 2)) / 2.0; } }private int getKthNum(int A[], int B[], int startA, int endA, int startB, int endB, int k) { int m = endA - startA + 1; int n = endB - startB + 1; // k = 1 直接返回最小的。 if (k == 1) { return Math.min(A[startA], B[startB]); } // 保证 A数组元素小于等于B数组元素 if (m < n) { return getKthNum(B, A, startB, endB, startA, endA, k); } if (m == 0) { return B[startB + k - 1]; } int posA = Math.min(m, k / 2); int posB = k - posA; // keep posA + posB = k if (A[startA + posA - 1] == B[startB + posB - 1]) { return A[startA + posA - 1]; // 减去B的左边和 A的右边, 注意边界 } else if (A[startA + posA - 1] > B[startB + posB - 1]) { return getKthNum(A, B, startA, startA + posA - 1 , startB + posB, endB, k - posB); // 减去A的左边和 B的右边, 注意边界 } else { return getKthNum(A, B, startA + posA, endA , startB, startB + posB - 1, k - posA); }}
0 0
- LeetCode: Median of Two Sorted Arrays
- LeetCode Median of Two Sorted Arrays
- leetcode 26: Median of Two Sorted Arrays
- Leetcode 4 Median of Two Sorted Arrays
- [Leetcode] Median of Two Sorted Arrays
- LeetCode 4 - Median of Two Sorted Arrays
- [LeetCode]Median of Two Sorted Arrays
- leetcode Median of Two Sorted Arrays
- LeetCode-Median of Two Sorted Arrays
- [LeetCode] Median of Two Sorted Arrays
- [LeetCode] Median of Two Sorted Arrays
- [leetcode] Median of Two Sorted Arrays
- leetcode-004:Median of Two Sorted Arrays
- Leetcode 4 Median of Two Sorted Arrays
- leetcode之 median of two sorted arrays
- 【转载】【leetcode】Median of Two Sorted Arrays
- LeetCode - Median of Two Sorted Arrays
- [LeetCode]Median of Two Sorted Arrays
- 面向对象
- 动态刷新ListView
- 一种VS2010配置OPENCV的方法
- 图的邻接表的建立 c++
- 找数组中第二大的数字
- [LeetCode] Median of Two Sorted Arrays
- 获取(多)屏幕尺寸--C++
- smail语法简析(1)
- POJ1426_Find The Multiple_测试出真知
- Dword、LPSTR、LPWSTR、LPCSTR、LPCWSTR、LPTSTR、LPCTSTR
- Java中的循环结构
- 正则表达式基本语法学习
- 从cin>>ch, cin.get(ch)看C++的参数引用
- MFC Windows应用程序设计——学习笔记【1】