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];
            }
  • 相关阅读:
    .NET Framework 概述
    .Net笔试(二)
    EF CodeFirst 创建数据库
    C#中的继承
    SqlHelper 基类
    在C#中实现OOP概念
    索引器、委托和事件
    .Net笔试(一)
    HTML标签速记整理W3C
    Java函数调用总结
  • 原文地址:https://www.cnblogs.com/pengdotnet/p/Median-of-Two-Sorted-Arrays.html
Copyright © 2011-2022 走看看