---
# System prepended metadata

title: (LeetCode)4. Median of Two Sorted Arrays

---

# (LeetCode)4. Median of Two Sorted Arrays

https://leetcode.com/problems/median-of-two-sorted-arrays/

###### Hard

##### Description
> Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.
> 
> Follow up: The overall run time complexity should be O(log (m+n)).
##### Example
> Input: nums1 = [1,3], nums2 = [2]
> Output: 2.00000
> Explanation: merged array = [1,2,3] and median is 2.

##### Solution
```python=

class Solution:
    def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:

        merge = []

        p1 = 0
        p2 = 0

        count1 = len(nums1)
        count2 = len(nums2)

        while p1 < count1 or p2 < count2:

            if p1 < count1 and p2 < count2:
                x = nums1[p1]
                y = nums2[p2]
                if x < y:
                    merge.append(x)
                    p1 += 1
                else:
                    merge.append(y)
                    p2 += 1

            elif p1 == count1 and p2 < count2:
                merge.append(nums2[p2])
                p2 += 1

            elif p2 == count2 and p1 < count1:
                merge.append(nums1[p1])
                p1 += 1

        count = len(merge)

        if count % 2 == 0:
            m = count//2
            return (merge[m-1] + merge[m])/2

        m = (count + 1) // 2

        return merge[m-1]
```

