Tuesday, September 15, 2015

[LeetCode] 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)).

class Solution {
public:
    double findK(vector<int>& nums1, int s1, 
                vector<int>& nums2, int s2, int k)
    {
        if(s1>=nums1.size()) return nums2[s2+k-1];
        if(s2>=nums2.size()) return nums1[s1+k-1];
        
        if(k == 1) return min(nums1[s1], nums2[s2]);
        
        int n1 = s1+k/2-1 < nums1.size() ? nums1[s1+k/2-1] : INT_MAX;
        int n2 = s2+k/2-1 < nums2.size() ? nums2[s2+k/2-1] : INT_MAX;
        
        if(n1 > n2)
        {
            return findK(nums1, s1, nums2, s2+k/2, k- k/2);
        }
        else
        {
            return findK(nums1, s1+k/2, nums2, s2, k- k/2);
        }
    }   
    
    double findMedianSortedArrays(vector<int>& nums1, 
                            vector<int>& nums2) {
        int l1 = nums1.size(), l2 = nums2.size();
        if((l1 + l2) % 2 == 0)
        {
            return (findK(nums1, 0, nums2, 0, (l1+l2)/2) + findK(nums1, 0, nums2, 0, (l1+l2)/2+1))/2;
        }
        
        return findK(nums1, 0, nums2, 0, (l1+l2)/2+1);
    }
};