Chinaunix首页 | 论坛 | 博客
  • 博客访问: 77170
  • 博文数量: 29
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 225
  • 用 户 组: 普通用户
  • 注册时间: 2014-03-06 15:31
文章分类

全部博文(29)

文章存档

2015年(18)

2014年(11)

我的朋友

分类: Java

2015-01-14 17:44:08

题目:
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.         double result;
  4.         int m = A.length;
  5.         int n = B.length;
  6.         if(m == 0){
  7.             result = findMedian(B);
  8.             return result;
  9.         }
  10.         else if(n == 0){
  11.             result = findMedian(A);
  12.             return result;
  13.         }
  14.         int i = 0, j = 0;
  15.         int num[] = new int[m+n];
  16.         while(i < m && j < n){
  17.             if(A[i] < B[j]){
  18.                 num[i+j] = A[i];
  19.                 i++;
  20.             }
  21.             else{
  22.                 num[i+j] = B[j];
  23.                 j++;
  24.             }
  25.         }
  26.         if(i == m){
  27.             while(j < n){
  28.                 num[i+j] = B[j];
  29.                 j++;
  30.             }
  31.         }
  32.         if(j == n){
  33.             while(i < m){
  34.                 num[i+j] = A[i];
  35.                 i++;
  36.             }
  37.         }
  38.         System.out.print(Arrays.toString(num));
  39.         result = findMedian(num);
  40.         return result;
  41.     }
  42.     
  43.     public double findMedian(int b[]){
  44.         double result;
  45.         int len = b.length;
  46.         if(len%2 == 0){
  47.             result = ((double)b[len/2]+(double)b[len/2-1])/2;
  48.         }
  49.         else{
  50.             result = (double)b[(len-1)/2];
  51.         }
  52.         return result;
  53.     }
  54. }

                                                                            
阅读(704) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~