您的位置:首页 > 编程语言 > C#

LeetCode #4 Median of Two Sorted Arrays C# Solution

2016-04-14 09:19 621 查看
LeetCode #4 Problem

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)).

这道题应该是在算法导论上出现过,不过算法导论上是两个长度相同的有序数组,而这里变成了两个长度不定甚至可以为空的数组。这增大了很多判断的条件。

具体算法最开始想到的是两个数组归并排序直到排到中位数的下标,这样的时间复杂度是O(m+n),然而题目要求是O(log(m+n))时间复杂度的算法。

然后想到log一般是二分类题目常见的时间复杂度,所以可以这么想,对于A[]和B[],如果A[MID] == B[MID],那么,显然这个就是中位数。对于其他情况,如果A.Length < B.Length,那么交换A和B。如果A[MID] > B[MID],那么可以显然中位数不会存在在A[0…MID]和B[MID…B.Length]的区间中,这样理想情况下一次就可以将规模减半,然后递归查找,终止条件就是A只剩下一个元素。

这个题最重要的就是细节的处理,小数据尤其是空数组的情况需要判断。

参考:/article/7668495.html

C# Code
public class Solution
{
int min(int a,int b)
{
if (a > b) return b; else return a;
}
double findKth(int[] a, int[] b, int k)
{
int m = a.Length;
int n = b.Length;
if (m > n) return findKth(b, a, k);
if (m == 0) return b[k - 1];
if (k == 1) return min(a[0], b[0]);
int pa = min(k / 2, m), pb = k - pa;
if (a[pa - 1] < b[pb - 1])
{
int[] temp = new int[a.Length];
Array.Copy(a, pa, temp, 0, a.Length - pa);
return findKth(temp, b, k - pa);
}
else if (a[pa - 1] > b[pb - 1])
{
int[] temp = new int[b.Length];
Array.Copy(b, pb, temp, 0, b.Length - pb);
return findKth(a, temp, k - pb);
}
else
return a[pa - 1];
}
public double FindMedianSortedArrays(int[] nums1, int[] nums2)
{
int m = nums1.Length, n = nums2.Length, total = m + n;

if (m == 1 && n == 0) return (nums1[0]);
if (m == 0 && n == 1) return (nums2[0]);
if (total<10000)
{
int[] temp = new int[total];
nums1.CopyTo(temp, 0);
nums2.CopyTo(temp, m);
Array.Sort(temp);
if ((total % 2) == 1)
{
return temp[temp.Length / 2];
}
else return ((temp[temp.Length / 2] + temp[temp.Length / 2 - 1]) / 2.0);
}
if (m == 1 && n == 1) return ((nums1[0] + nums2[0]) / 2.0);
if ((total % 2) == 1)
return findKth(nums1, nums2, total / 2 + 1);
else
return (findKth(nums1, nums2, total / 2)
+ findKth(nums1, nums2, total / 2 + 1)) / 2;
}
};


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: