LeetCode 4 双数组找中位数

来源:互联网 发布:咖啡网络课程 编辑:程序博客网 时间:2024/06/06 16:26

虽然是hard 但是我觉得比前面都简单

运用了归并排序 其实就是分治算法书上的例题最后一步 计算复杂度是O(n)然后找中位数就好



c# code


public class Solution
{
    public double FindMedianSortedArrays(int[] nums1, int[] nums2)
    {
        if(nums1.Length==0&&nums2.Length==0)
        {
            return 0;
        }
        int[] array=new int[nums1.Length+nums2.Length];
        int index=0,a=0,b=0;
        while(a<nums1.Length&&b<nums2.Length)
        {
            if(nums1[a]<=nums2[b])
            {
                array[index]=nums1[a];
                a++;
                index++;
            }
            else
            {
                array[index]=nums2[b];
                b++;
                index++;
            }
        }
        if(a<nums1.Length&&nums1.Length==nums2.Length)
        {
            array[index]=nums1[a];
        }
        if(b<nums2.Length&&nums1.Length==nums2.Length)
        {
            array[index]=nums2[b];
        }
        if(nums1.Length>nums2.Length)
        {
            while(a<nums1.Length)
            {
                array[index]=nums1[a];
                a++;
                index++;
            }
        }
        if(nums1.Length<nums2.Length)
        {
            while(b<nums2.Length)
            {
                array[index]=nums2[b];
                b++;
                index++;
            }
        }
        double result=0;
        if(array.Length%2==0)
        {
            result=((double)array[(array.Length-1)/2]+(double)array[(array.Length)/2])/2.0;
        }
        else
        {
            result=(double)array[(array.Length-1)/2];
        }
        return result;
    }
}


0 0