python solution,easy to understand


  • 0
    S
    class Solution(object):
        def findMedianSortedArrays(self, nums1, nums2):
            """
            :type nums1: List[int]
            :type nums2: List[int]
            :rtype: float
            """
            median_idx = (len(nums1) + len(nums2)) // 2
            index1, index2 = 0, len(nums1)
            combine_list = nums1 + nums2
            new_list = []
            i = 0
    
            while i <= median_idx:
                if index1 < len(nums1) and index2 - len(nums1) < len(nums2):
                    new_list.append(min(combine_list[index1], combine_list[index2]))
                    if combine_list[index1] < combine_list[index2]:
                        index1 += 1
                    else:
                        index2 += 1
                elif index1 >= len(nums1):
                    # nums1 is out of range, append nums2
                    new_list.append(combine_list[index2])
                    index2 += 1
                elif index2 >= len(nums2):
                    # nums2 is out of range, append nums1
                    new_list.append(combine_list[index1])
                    index1 += 1
                i += 1
    
            if (len(nums1) + len(nums2)) % 2 == 0:
                median = float(new_list[median_idx] + new_list[median_idx - 1]) / 2
            else:
                median = new_list[median_idx]
    
            return median
    

Log in to reply
 

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