您的位置:首页 > 其它

leetcode 刷题日记——Median of Two Sorted Arrays

2017-08-22 11:48 507 查看
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

看到此题第一反应就是归并排序,然后求出中位数。
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int m=nums1.length;
int n=nums2.length;
int[] com =new int[m+n];
int k=0,i=0,j=0;
while( i<m || j<n){
while(i<m&&j<n){
if(nums1[i]<=nums2[j]) com[k++]=nums1[i++];
else com[k++]=nums2[j++];
}
while(i<m) com[k++]=nums1[i++];
while(j<n) com[k++]=nums2[j++];
}
if((m+n)%2==0)
return (double)0.5*(com[(m+n)/2-1]+com[(m+n)/2]);
else
return  (double)com[(m+n)/2];
}
}

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: