leetcode-个人题解4

LEETCODE专题


4. Median of Two Sorted Arrays

首先先上个题目要求:

这个题目要求要仔细看,我之前就是因为没仔细看导致审错了题,3次。。。
题目大意就是说:给定两个有序数组,找出它们有序拼接之后的中位数。

之前审错题的分析就免了吧,现在我们直接来考虑正确的做法和问题。

  • 问题
    • 如何把两个数组有序地拼接在一起
    • 如何在有序数组中寻找中位数

对于第二个问题,我想就算是编程入门的朋友也不会花太多时间,就留给读者自己解决吧。我们着重来探讨下如何解决第一个问题。

思路也很简单,其实就是设置两个数组的游标,然后比较游标对应的数组元素,取小的元素并且将相应的游标+1。这样一趟过后就可以实现有序拼接了。而因为中位数并不需要我们把最终数组的中位数之后的元素也给加进去,所以笔者的循环做到中位数那里就停止了。最后按照中位数的求法直接求出中位数就可以了。

代码如下:

class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        /* The total_array is to store all the two array,
         * which ends at the (nums1.size() + nums2.size() / 2),
         * because that's enough to compute the median
         */
        int total_array[nums1.size() + nums2.size()];
        for (int i = 0, j = 0; i <= nums1.size() || j <= nums2.size(); ) {
            /* The IF ELSE block is to judge whose size is zero,
             * or if the index is at the end, or to compare the
             * corresponding number. Then, we put
             * the proper number in the total_array
             */
            if (nums1.size() == 0 || i == nums1.size()
                || (nums2.size() > 0 && j < nums2.size() && nums1[i] > nums2[j]) ) {
                total_array[i + j] = nums2[j];
                j++;
            } else if (nums2.size() == 0 || j == nums2.size() || nums1[i] <= nums2[j]) {
                total_array[i + j] = nums1[i];
                i++;
            }
            if (i + j - 1>= (nums1.size() + nums2.size() ) / 2) break;
        }
        double median = ( (double)total_array[(nums1.size() + nums2.size() ) / 2] +
                          (double)total_array[(nums1.size() + nums2.size()  - 1 ) / 2] ) / 2;
        return median;
    }
};

时间复杂度:O(m + n)
空间复杂度:O(m + n)

猜你喜欢

转载自blog.csdn.net/m0_37576233/article/details/77966491