您的位置:首页 > 其它

Median of Two Sorted Arrays(两个有序数组的中位数)

2017-03-06 21:28 537 查看
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



求两个有序数组的中位数:

主要使用的办法是,合并排序中所使用的。在合并排序中,首先将序列分成两部分,将两部分各自排序,再将已排序的两部分合并。

具体方法是:先取序列1和序列2中最小的元素,若为顺序的话,则为序列1和序列2的首元素,比较两个元素的大小,若A1[0] > A2[0],则A2[0]为最小的元素,

再比较A1[0] 和A2[1],较小的元素为第二小的元素,反之,A1[0]为最小元素,再比较A1[1] 和 A2[0],较小的为第二小的元素。

依次类推,遍历两个数组的所有元素。

所需的时间复杂度为O(log (m+n)),其中m和n为两个数组的各自大小。

基于上述原理,判断m+n是偶数还是奇数,若为偶数,

则中位数为第(m+n)/2 和 (m+n)/2 + 1大的元素的平均值

若为奇数,则中位数为(m+n)/2
+ 1大的元素的值。

代码如下(不知道怎么写整洁一点。。。):class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int n = nums1.size();
int m = nums2.size();
int i = 0,j = 0;
int s = m + n;
double odd;
if(s%2 == 0){
odd = 0;
}
else
odd = 1;
s /= 2;
int count = 0;
int num1,num2;
while(i < n && j < m) {
count ++;
if(nums1[i] > nums2[j]) {
if(count == s) {
num1 = nums2[j];
}
else if(count == s+1) {
num2 = nums2[j];
}
++j;
}
else {
if(count == s) {
num1 = nums1[i];
}
else if(count == s+1) {
num2 = nums1[i];
}
++i;
}
}
if(i == n) {
if(s + 1 > count){
num2 = nums2[j + s - count];
}
if(s > count) {
num1 = nums2[j + s - count - 1];
}
}
else if(j == m) {
if(s + 1 > count){
num2 = nums1[i + s - count];
}
if(s > count) {
num1 = nums1[i + s - count - 1];
}
}
if (odd){
return num2;
}
else
return (num1+num2)/2.0;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐