C++ Solution - Decent Length, but Not That Fast -- Any Suggestions?


  • 0
    A
    class Solution {
    public:
        double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
            vector<int> combined_nums; 
            int i = 0, j = 0;
            while(i < nums1.size() && j < nums2.size()){
                if (nums1[i] < nums2[j]){
                    combined_nums.push_back(nums1[i]);
                    i++; 
                }
                else{
                    combined_nums.push_back(nums2[j]);  
                    j++; 
                }
            }
            while (i < nums1.size()){
                combined_nums.push_back(nums1[i]);
                i++; 
            }
            while (j < nums2.size()){
                combined_nums.push_back(nums2[j]); 
                j++;
            }
            // combined_nums has (i+j) elements 
            
            int mid = (i + j)/2; 
            
            // if even, the median will be an average of two middle numbers
            if ( (i+j)%2 == 0 ) 
                return (double) (combined_nums[mid-1] + combined_nums[mid])/2; 
            return (double) combined_nums[mid]; 
        }
    };

Log in to reply
 

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