Skip to content

Commit 0828b8a

Browse files
author
applewjg
committed
Median of Two Sorted Arrays
1 parent b788941 commit 0828b8a

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

MedianofTwoSortedArrays.java

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/*
2+
Author: King, [email protected]
3+
Date: Dec 12, 2014
4+
Problem: Median of Two Sorted Arrays
5+
Difficulty: Hard
6+
Source: http://leetcode.com/onlinejudge#question_4
7+
Notes:
8+
There are two sorted arrays A and B of size m and n respectively.
9+
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
10+
11+
Solution: 1. O(m+n)
12+
2. O(log(m+n))
13+
*/
14+
15+
public class Solution {
16+
public double findMedianSortedArrays_1(int A[], int B[]) {
17+
int m = A.length, n = B.length;
18+
int total = n + m, m1=0, m2=0, i=0, j=0;
19+
for (int k = 1; k <= total/2 + 1; ++k) {
20+
int a = (i==m) ? Integer.MAX_VALUE : A[i];
21+
int b = (j==n) ? Integer.MAX_VALUE : B[j];
22+
m1 = m2;
23+
m2 = Math.min(a,b);
24+
if (a > b) ++j;
25+
else ++i;
26+
}
27+
if ((total&1) == 1) return m2;
28+
else return (m1+m2)/2.0;
29+
}
30+
public double findMedianSortedArrays_2(int A[], int B[]) {
31+
int m = A.length, n = B.length;
32+
int total = m + n;
33+
int k = total / 2;
34+
if ((total&1) == 1) return findKth(A,B,k+1,0,m-1,0,n-1);
35+
else return (findKth(A,B,k,0,m-1,0,n-1)+findKth(A,B,k+1,0,m-1,0,n-1))/2.0;
36+
}
37+
public double findKth(int A[], int B[], int k, int astart, int aend, int bstart, int bend) {
38+
int alen = aend - astart + 1;
39+
int blen = bend - bstart + 1;
40+
if (alen > blen) return findKth(B,A,k, bstart, bend, astart, aend);
41+
if (alen == 0) return B[bstart + k - 1];
42+
if (k == 1) return Math.min(A[astart],B[bstart]);
43+
int sa = Math.min(alen, k/2), sb = k- sa;
44+
if (A[astart+sa-1] == B[bstart+sb-1]) return A[astart+sa-1];
45+
else if (A[astart+sa-1] > B[bstart+sb-1]) return findKth(A,B,k - sb,astart,aend,bstart+sb,bend);
46+
else return findKth(A,B,k - sa,astart+sa,aend,bstart,bend);
47+
}
48+
49+
}

0 commit comments

Comments
 (0)