您的位置:首页 > 其它

LeetCode-4. Median of Two Sorted Arrays

2016-10-29 20:29 417 查看
1.问题描述

There are two sorted arrays nums1 and nums2 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)).

Example 1:

nums1 = [1, 3]
nums2 = [2]

The median is 2.0


Example 2:

nums1 = [1, 2]
nums2 = [3, 4]

The median is (2 + 3)/2 = 2.5

2.算法思路

这道题是求两排列序列的中位数,并且要求了算法的时间复杂度,因为是两个排列的数列,所以当时很自然的想到了归并排序。

3.Java代码

public class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int len1=nums1.length;
int len2=nums2.length;
int[] totalNum=new int[len1+len2];
len1--;
len2--;
int i=0;
while(len1>=0&&len2>=0){
if(nums1[len1]>nums2[len2])
totalNum[i++]=nums1[len1--];
else
totalNum[i++]=nums2[len2--];

}
while(len1>=0){
totalNum[i++]=nums1[len1--];
}
while(len2>=0){
totalNum[i++]=nums2[len2--];
}
int len=nums1.length+nums2.length;
if(len%2==0){
return (totalNum[len/2]+totalNum[len/2-1])/(float)2;
}
else{
return totalNum[len/2];
}

}
}PS:LeetCode的论坛里面提供了一种时间复杂度为O(log(min(m+n)))的算法,简单易懂,但是目前还没调出来。链接:https://discuss.leetcode.com/topic/4996/share-my-o-log-min-m-n-solution-with-explanation/52
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: