C++ solution, only check half numbers


  • -1
    J
    class Solution {
    public:
        double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
    // insert to 3rd vector, but stop around middle
            vector<int> v; //new empty vector
            int i=0;    //index of nums1
            int j=0;    //index of nums2
    
            int s1=nums1.size();
            int s2=nums2.size();
            int half = (s1+s2)/2;  //if s1=2 s2=3  half=2    if s1=2 s2=2 half = 2
            
            while (i+j <= half ) {
                if (i==s1) 
                    v.push_back(nums2[j++]);
                else if (j==s2) 
                    v.push_back(nums1[i++]);
                else 
                    (nums1[i]<nums2[j]) ?  v.push_back(nums1[i++]) : v.push_back(nums2[j++]);
            }
            return (s1+s2)%2 ?    v[half] : (0.5*(v[half-1]+v[half])) ; //odd  : even result        
        }
    };
    

Log in to reply
 

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