• 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];
            }
  • 相关阅读:
    阿牛的EOF牛肉串
    盐水的故事
    密码
    Digital Roots
    不容易系列之(3)—— LELE的RPG难题
    不容易系列之一
    超级楼梯
    母牛的故事
    蟠桃记
    Children’s Queue
  • 原文地址:https://www.cnblogs.com/pengdotnet/p/Median-of-Two-Sorted-Arrays.html
Copyright © 2020-2023  润新知