码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Median of Two Sorted Arrays

时间:2014-12-23 23:49:51      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:

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 }

 

LeetCode Median of Two Sorted Arrays

标签:

原文地址:http://www.cnblogs.com/birdhack/p/4181358.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!