LeetCode-Median of Two Sorted Arrays

来源:互联网 发布:造价软件排名 编辑:程序博客网 时间:2024/05/01 12:05

LeetCode-Median of Two Sorted Arrays

想不到距离上次刷LeetCode已经有两年了,惭愧惭愧。希望这次能坚持刷下去,先全部刷完LeetCode再刷其他的oj系统。博客以后只用来整理经典、有意义的问题


今天写的是一道经典的查找题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)).

分析

在两个排序好的数组中找出它们的中值,并且要求时间复杂度为O(log (m+n))。这道题可以把它转换为在两个排序的数组中找第k大的元素。不考虑时间复杂度,最直观的解法是直接merge两个数组,然后排序,输出第k个元素即可。这样时间复杂度为O(m + n)。
不过,对于两个排序好的数组,我可以不用排序这么昂贵的操作。我们可以使用双指针,pa、pb分别指向A、B两个数组的开头。如果(pa)<(pb),则pa++, m++;反之,如果(pb)<(pa),则pb++, m++。当m等于k时,就得到了我们的答案。时间复杂度O(k),空间复杂度O(1)。但当k很大是,时间复杂度还是趋向于于O(m + n)。
其实上面的方法还是没有很好运用排序数组的性质。对于排序数组查找,较好的方法自然是二分查找。
我们假设A、B的大小都大于k/2,然后比较A[k/2]与B[k/2]的大小,如果A[k/2]

代码

一、循环版本

class Solution {public:    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {        int size1 = nums1.size(), size2 = nums2.size();        if ((size1 + size2) % 2 == 0)            return (findTheKnum(nums1, nums2, (size1 + size2) / 2) + findTheKnum(nums1, nums2, (size1 + size2) / 2 + 1)) / 2.0;        else            return findTheKnum(nums1, nums2, (size1 + size2) / 2 + 1);    }    int findTheKnum(vector<int>& nums1, vector<int>& nums2, int k)    {        int first1, first2, last1, last2, k1, k2;        first1 = first2 = 0;    //代表数组起始索引        last1 = nums1.size() - 1;   //代表数组末尾索引        last2 = nums2.size() - 1;        while (first1 <= last1 && first2 <= last2)        {            int size1 = last1 - first1 + 1;            int size2 = last2 - first2 + 1;            if (k == 1)            {                return nums1[first1] < nums2[first2] ? nums1[first1] : nums2[first2];            }            k1 = k / 2;            k2 = k - k1;     //保证无论k为奇偶时都有k1+k2 等于k            if (k1 > size1)   //判断k1、k2 是否越界            {                k1 = size1;                k2 = k - k1;            }            else if (k2 > size2)            {                k2 = size2;                k1 = k - k2;            }            if (nums1[first1 + k1 - 1] == nums2[first2 + k2 - 1])            {                return nums1[first1 + k1 - 1];            }            else if (nums1[first1 + k1 - 1] < nums2[first2 + k2 - 1])            {                first1 += k1;                k -= k1;            }            else            {                first2 += k2;                k -= k2;            }        }        if (first1 > last1)  //nums1为空        {            return nums2[first2 + k - 1];        }        if (first2 > last2)  //nums2为空        {            return nums1[first1 + k - 1];        }    }};
原创粉丝点击