Very simple Python solution O(m+n) Accepted


  • 0
    L

    I understand that the question asks us for an O(log(m+n)) solution but my O(m+n) solution was accepted and beats 60% of the submissions. So just posting it here:

    class Solution(object):
        def mergeTwoSortedArrays(self, nums1, nums2):
            i,j, res = 0,0, []
            while i<len(nums1) and j<len(nums2):
                if nums1[i] < nums2[j]:
                    res.append(nums1[i])
                    i += 1
                else:
                    res.append(nums2[j])
                    j += 1
            if i < len(nums1):
                res.extend(nums1[i:])
            elif j < len(nums2):
                res.extend(nums2[j:])
            return res
            
        def findMedianSortedArrays(self, nums1, nums2):
            """
            :type nums1: List[int]
            :type nums2: List[int]
            :rtype: float
            """
            ml = self.mergeTwoSortedArrays(nums1, nums2)
            midI = len(ml)/2 
            if len(ml)%2 == 0:
                return float( float(ml[midI] + ml[midI-1])/2 ) 
            return ml[midI]
        
            
    

Log in to reply
 

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