美文网首页
4. Median of Two Sorted Arrays

4. Median of Two Sorted Arrays

作者: _SANTU_ | 来源:发表于2017-01-06 01:55 被阅读0次

    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++ Version:

    class Solution {
    public:
        double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
            int m, n;
            double result;
            m = nums1.size();
            n = nums2.size();
            vector<int> nums3;
            int p1 = 0, p2 = 0;
            
            if( (m + n) % 2){   //总共有奇数个,取第(m+n+1)/2个
                int k = (m+n+1)/2;
                while(p1<m&&p2<n&&k){
                    nums3.push_back(nums1[p1]<nums2[p2]?nums1[p1++]:nums2[p2++]);
                    k--;
                }
                while(p1<m&&k){
                    nums3.push_back(nums1[p1++]);
                    k--;
                }
                while(p2<n&&k){
                    nums3.push_back(nums2[p2++]);
                    k--;
                }
                result = nums3[ (m + n -1) / 2];
            }else{  //偶数个,取第(m+n)/2个和第(m+n+2)/2的平均值
                int k = (m+n+2)/2;
                while(p1<m&&p2<n&&k){
                    nums3.push_back(nums1[p1]<nums2[p2]?nums1[p1++]:nums2[p2++]);
                    cout << k  << endl;
                    k--;
                }
                while(p1<m&&k){
                    nums3.push_back(nums1[p1++]);
                    cout << k  << endl;
                    // cout << nums1[p1++];
                    k--;
                }
                while(p2<n&&k){
                    nums3.push_back(nums2[p2++]);
                    cout << k  << endl;
                    // cout << nums2[p2++];
                    k--;
                }
                // cout << m+n << (double)nums3[ (m+n) / 2] << " " << (double)nums3[ (m+n) / 2];
                result = ( (double)nums3[ (m+n-2) / 2] + (double)nums3[(m+n) / 2] ) / 2;
            }
            return result;
        }
    };
    

    相关文章

      网友评论

          本文标题:4. Median of Two Sorted Arrays

          本文链接:https://www.haomeiwen.com/subject/jljtbttx.html