zoukankan      html  css  js  c++  java
  • LeetCode 4. Median of Two Sorted Arrays

            public double FindMedianSortedArrays(int[] nums1, int[] nums2)
            {
                int m = nums1.Length;
                int n = nums2.Length;
                int total = m + n;
                if (total % 2 == 1)
                    return findKth(nums1, m, nums2, n, total / 2 + 1);
                else
                    return (findKth(nums1, m, nums2, n, total / 2)
                            + findKth(nums1, m, nums2, n, total / 2 + 1)) / 2;
            }
    
            //比较a[k/2] 和b[k/2], 将较小的那个数组的前k/2部分删除;循环这个过程
            double findKth(int[] a, int m, int[] b, int n, int k)
            {
                //always assume that m is equal or smaller than n  
                if (m > n)
                    return findKth(b, n, a, m, k);
                if (m == 0)
                    return b[k - 1];
                if (k == 1)
                    return Math.Min(a[0], b[0]);
                //divide k into two parts  
                int pa = Math.Min(k / 2, m), pb = k - pa;
                if (a[pa - 1] < b[pb - 1])
                {
                    int[] newA = a.Skip(pa).ToArray();
                    return findKth(newA, m - pa, b, n, k - pa);
                }
                else if (a[pa - 1] > b[pb - 1])
                {
                    int[] newB = b.Skip(pb).ToArray();
                    return findKth(a, m, newB, n - pb, k - pb);
                }
                else
                    return a[pa - 1];
            }
  • 相关阅读:
    Python Virtualenv 虚拟环境
    二叉树的左视图和右视图
    Vxlan简介
    2、程序的基本结构
    chef cookbook 实战
    eclipse 搭建ruby环境
    linux 安装软件出现/tmp 磁盘不足时 解决方案
    Python 可变对象与不可变对象
    Chapter 4-5
    Chapter 3
  • 原文地址:https://www.cnblogs.com/pengdotnet/p/Median-of-Two-Sorted-Arrays.html
Copyright © 2011-2022 走看看