4. Median of Two Sorted Arrays

2017-01-06  本文已影响0人  _SANTU_

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;
    }
};
上一篇下一篇

猜你喜欢

热点阅读