Median of Two Sorted Arrays
来源:互联网 发布:linux informix 安装 编辑:程序博客网 时间:2024/06/02 23:45
题目: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)).
leetcode将这个问题转换为求第k个元素,k的值为(A's length + B' Length)/2。
如果其中一个为空,在第k个是不为空的第k个元素;如果k为0,则为a或b的
较小的第一个元素。
public static double findMedianSortedArrays(int A[], int B[]) { int m = A.length; int n = B.length; if ((m + n) % 2 != 0) // odd return (double) findKth(A, B, (m + n) / 2, 0, m - 1, 0, n - 1); else { // even return (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 cases if (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 count int bMid = k - aMid - 1; // b's middle count // make aMid and bMid to be array index aMid = 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
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of two sorted arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- median-of-two-sorted-arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Median of Two Sorted Arrays
- Longest Palindromic Substring
- 小胖说事29-----iOS中Navigation中左滑pop页面的三种方法
- Caused by: java.lang.NoClassDefFoundError: org/springframework/web/context/WebApplicationContext
- C#和.Net联系
- 【机房重构】SQL语句已终止
- Median of Two Sorted Arrays
- 每天一个小知识点3(原型与构造函数总结一)
- 冒泡方排序
- Linux下执行ping命令创建得到的进程的有效用户不是root
- noi模板-HDU1269-强连通分量
- Hive Cilent数据操作
- 一个非常strong的编程学习方法
- 标准I/O文件复制,文件I/O文件复制
- LOAD DATA LOCAL INFILE