您的位置:首页 > 其它

[leet code 4] Median of Two Sorted Arrays

2015-02-09 21:55 204 查看
1 题目

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)).

2 思路

这题比较简单,实现的其实就是归并排序merge那个部分。

3 代码

public class MedianOfTwoSortedArrays {
public double findMedianSortedArrays(int A[], int B[]) {
double median = 0;
int sum = A.length + B.length;
int[] C = new int[sum];
int c = 0;
int a = 0;
int b = 0;
while(a < A.length && b < B.length){
if (A[a] > B[b]) {
C[c] = B[b];
b++;
c++;
}else {
C[c] = A[a];
a++;
c++;
}
}
while (a < A.length) {
C[c] = A[a];
c++;
a++;
}
while(b < B.length){
C[c] = B[b];
c++;
b++;
}

if (sum % 2 == 0) {
median = (double) (C[sum/2] + C[sum/2 - 1])/2;
}else {
median = C[sum/2];
}
System.out.println(median);
return median;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: