Leetcode刷题C#版之 Median of Two Sorted Arrays

题目:

There are two sorted arrays nums1 and nums2 of size m and n respectively.

Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).

Example 1:

nums1 = [1, 3]
nums2 = [2]

The median is 2.0

 

Example 2:

nums1 = [1, 2]
nums2 = [3, 4]

The median is (2 + 3)/2 = 2.5

C#版本的代码如下(关键步骤已经注释):
        //这道题目是一个并归排序的思想;已知有两个排好序的序列再排序
        public static double FindMedianSortedArrays(int[] nums1, int[] nums2)
        {
            double result = 0;
            //定义两个游标尺分别标记两个数组的不同位置
            int i = 0;
            int j = 0;
            //存放新的序列
            List<int> intresult = new List<int>();
            //循环直到一个序列全部排序完成
            while (nums1.Length > i && nums2.Length > j)
            {
                //将小的数字放入新的序列中
                if (nums1[i] >= nums2[j])
                {
                    intresult.Add(nums2[j]);
                    j++;
                }
                else
                {
                    intresult.Add(nums1[i]);
                    i++;
                }
            }
            //判断哪个数组没有排完序,将之全部放入新的序列中
            if (j >= nums2.Length)
            {
                while (nums1.Length > i)
                {
                    intresult.Add(nums1[i]);
                    i++;
                }
            }
            else if (i >= nums1.Length)
            {
                while (nums2.Length > j)
                {
                    intresult.Add(nums2[j]);
                    j++;
                }

            }
            //计算中间值
            if (intresult.Count % 2 == 0)
            {
                result = (intresult[intresult.Count / 2] + intresult[intresult.Count / 2 - 1]) / 2.0;
            }
            else
            {
                result = intresult[intresult.Count / 2];
            }
            return result;
        }

这里代码跑出来的时间为:156 ms,超过了所有提交代码的时间,小小的炫耀一下:

抛砖引玉还请大神多多指教

 




posted on 2018-02-23 14:03  矢雨星辰2012  阅读(198)  评论(0编辑  收藏  举报

导航