Comprehensive and simple solution with stl in O(m+n)


  • 0
    W
    1. merge the 2 vector in O(n)
    2. get the median value in O(1)
    #include  <algorithm>
    
    class Solution {
    public:
        double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
            nums1.insert(nums1.end(), nums2.begin(), nums2.end());
            std::sort(nums1.begin(), nums1.end());
            int size = nums1.size();
            if (size %2)
            {
                return nums1[size / 2];
            }
            else
            {
                return (nums1[size / 2 - 1] + nums1[size / 2]) / 2.0f;
            }
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.