12 lines iterative Python code in 112ms


  • 0
    T

    Algorithm is pretty strait forward. Always remove the max element from those 2 lists till only half of them.

    class Solution(object):
        def findMedianSortedArrays(self, nums1, nums2):
            even = (len(nums1) + len(nums2)) % 2 == 0
            half = (len(nums1) + len(nums2) + 1) // 2
            prev = curr = 0
            for i in range(half + even):
                prev = curr
                if len(nums1) == 0:
                    curr = nums2.pop()
                elif len(nums2) == 0:
                    curr = nums1.pop()
                else:
                    curr = nums1.pop() if nums1[-1] > nums2[-1] else nums2.pop()
    
            return float(curr + prev) / 2 if even == True else curr
    

Log in to reply
 

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