两个不同大小的排序数组的中位数

时间:2016-06-18 06:39:41

标签: c++ arrays binary-search

我是从极客那里为极客们http://www.geeksforgeeks.org/median-of-two-sorted-arrays-of-different-sizes/解决了这个问题,但是当我实现了相同的代码,然后输入 A [] = {1,2,3} B [] = {3,6,9,12} 它输出错误的输出为6但它应该是3,有人请告诉我代码的问题吗?

.idea
node_modules
bower_components
internal-docs

2 个答案:

答案 0 :(得分:1)

您只是忘记在medianOf4函数中将结果除以2.0,然后返回结果:

int medianOf4(int a, int b,int c,int d)//median of 4 numbers
{
    int maximum = max(a,max(b,max(c,d)));
    int minimum = min(a,min(b,min(c,d)));
    return ((a+b+c+d) - maximum - minimum) / 2.0; # <-- forgot to add "/ 2.0"
}

希望这有帮助!

答案 1 :(得分:0)

public class Solution {
public double FindMedianSortedArrays(int[] nums1, int[] nums2) {
    if(nums1== null || nums1.Length<1)
        return result(nums2);
    else if(nums2== null || nums2.Length<1)
        return result(nums1);

    int[] merged = new int[nums1.Length + nums2.Length];
    int num1Ind=0;
    int num2Ind=0;
    int currInd = 0;

    while(num1Ind<nums1.Length &&  num2Ind<nums2.Length){
        if(nums1[num1Ind]< nums2[num2Ind])
            merged[currInd++]=nums1[num1Ind++];
        else
            merged[currInd++]=nums2[num2Ind++];
    }

    if(num2Ind<nums2.Length)
        for(int i=num2Ind; i<nums2.Length; i++)
           merged[currInd++]=nums2[i];
    else if(num1Ind<nums1.Length)
        for(int i=num1Ind; i<nums1.Length; i++)
           merged[currInd++]=nums1[i];

    return result(merged);
}

private double result(int[] merged){
    if(merged.Length==1)
        return merged[0];
     if((merged.Length)%2 !=0)
        return (double)merged[merged.Length/2];
     return (double)(merged[merged.Length/2-1] + merged[merged.Length/2])/2;


}

}