Leetcode 004 Median of Two Sorted Arrays

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Gongzq5/article/details/81220013

Leetcode 004 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

My Solution (O(n) not O(logn))

class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        int len1 = nums1.size(), len2 = nums2.size();
        // if (len1 == 0 && len2 == 0) return 0;
        int position = (len1 + len2) / 2;
        bool odd = ((len1 + len2) % 2 == 1);
        // so postion is 
        // odd=false: (position-1, postion)/2
        // odd=true: position
        int curr = 0;
        int lst, now;
        int i = 0, j = 0;
        while (i < len1 || j < len2) {
            lst = now;
            if (i >= len1) {
                now = nums2[j];
                j++; 
            } else if (j >= len2) {
                now = nums1[i];
                i++; 
            } else {
                if (nums1[i]<nums2[j]) {now = nums1[i]; i++;}
                else {now = nums2[j]; j++;}             
            }           
            if (curr == position) {
                double re = odd ? (double)now : (double)(lst + now) / 2;
                return re;
            }
            curr++;
        }
    }
};

分析

思路很简单,其实就是把两个数组归并为一个数组,然后根据得到这个数组的中位数。

在实际中进行了一些优化:首先,不需要申请空间存储这个归并后的数组,只需要得到用来计算中位数的1或2个数字即可(即数字总数为奇数和偶数时);其次,不需要将数组的所有都计算出来,只需计算到中间位置即可。

因此该方法并没有达到真正的 O ( l o g ( m + n ) ) ,而是要遍历 ( m + n ) / 2 个元素,即 O ( ( m + n ) / 2 )

猜你喜欢

转载自blog.csdn.net/Gongzq5/article/details/81220013