Thursday, 8 June 2017

Median of Two Sorted Arrays (LeetCode)


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Solution {
public:
    
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        int l1 = nums1.size();
        int l2 = nums2.size();
        if(l1>l2)
            return findMedianSortedArrays(nums2, nums1);
        int k = (l1+l2-1)>>1;
        int lft = 0, rgt = l1;
        while(lft<rgt)
        {
            int md = (lft+rgt)>>1;
            if(nums1[md]<nums2[k-md])
                lft = md+1;
            else rgt = md;
        }
        double x, y;
        
        if(lft>0 && (k-lft)>=0) 
            x = max(nums1[lft-1], nums2[k-lft]);
        else if(lft>0)
            x = nums1[lft-1];
        else if(k-lft>=0)
            x = nums2[k-lft];
            
        if((l1+l2) & 1) return x; //total odd size, single median
        
        if(lft<l1 && (k-lft+1)<l2)
            y = min(nums1[lft], nums2[k-lft+1]);
        else if(lft<l1)
            y = nums1[lft];
        else if((k-lft+1)<l2)
            y = nums2[k-lft+1];
        return (x+y)/2.0;
        
    }      
    
};

No comments:

Post a Comment