LeetCode Median of Two Sorted Arrays

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

 

 1 public class Solution {
 2     public double findMedianSortedArrays(int A[], int B[]) {
 3         int la=A.length;
 4         int lb=B.length;
 5         int l=la+lb;
 6         int ia=0,ib=0;
 7         ArrayList<Integer> list = new ArrayList<Integer>();
 8         for (int i = 0; i < l; i++) {
 9             if (ia < la && ib < lb) {
10                 if (A[ia] < B[ib]) {
11                     list.add(A[ia]);
12                     ++ia;
13                 } else {
14                     list.add(B[ib]);
15                     ++ib;
16                 }
17             }else if (ia >= la && ib < lb) {
18                 list.add(B[ib]);
19                 ++ib;
20             }else if (ia < la && ib >= lb) {
21                 list.add(A[ia]);
22                 ++ia;
23             }
24 
25             if (list.size() == l / 2 + 1) {
26                 if (l % 2 == 1) {
27                     return list.get(list.size() - 1);
28                 } else {
29                     double last1 = list.get(list.size() - 1);
30                     double last2 = list.get(list.size() - 2);
31                     return (last1 + last2) / 2;
32                 }
33             }
34             
35             
36         } 
37 
38         return 0;
39 
40     }
41 }

 

posted @ 2014-12-23 22:58  birdhack  阅读(127)  评论(0编辑  收藏  举报