<p>Given two sorted arrays <code>nums1</code> and <code>nums2</code> of size <code>m</code> and <code>n</code> respectively, return <strong>the median</strong> of the two sorted arrays.</p>

<p>The overall run time complexity should be <code>O(log (m+n))</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> nums1 = [1,3], nums2 = [2]
<strong>Output:</strong> 2.00000
<strong>Explanation:</strong> merged array = [1,2,3] and median is 2.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> nums1 = [1,2], nums2 = [3,4]
<strong>Output:</strong> 2.50000
<strong>Explanation:</strong> merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>nums1.length == m</code></li>
	<li><code>nums2.length == n</code></li>
	<li><code>0 &lt;= m &lt;= 1000</code></li>
	<li><code>0 &lt;= n &lt;= 1000</code></li>
	<li><code>1 &lt;= m + n &lt;= 2000</code></li>
	<li><code>-10<sup>6</sup> &lt;= nums1[i], nums2[i] &lt;= 10<sup>6</sup></code></li>
</ul>

class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        // Ensure nums1 is the smaller array.
        if (nums1.size() > nums2.size()) {
            return findMedianSortedArrays(nums2, nums1);
        }
        int m = nums1.size();
        int n = nums2.size();
        int imin = 0, imax = m;
        int half_len = (m + n + 1) / 2;
        while (imin <= imax) {
            int i = (imin + imax) / 2;
            int j = half_len - i;
            if (i < m && nums2[j-1] > nums1[i]) {
                // i is too small, must increase it
                imin = i + 1;
            } else if (i > 0 && nums1[i-1] > nums2[j]) {
                // i is too big, must decrease it
                imax = i - 1;
            } else {
                // i is perfect
                int max_of_left = 0;
                if (i == 0) { 
                    max_of_left = nums2[j-1];
                } else if (j == 0) { 
                    max_of_left = nums1[i-1];
                } else { 
                    max_of_left = max(nums1[i-1], nums2[j-1]); 
                }
                if ((m + n) % 2 == 1) {
                    return max_of_left; // Odd case
                }
                int min_of_right = 0;
                if (i == m) { 
                    min_of_right = nums2[j];
                } else if (j == n) { 
                    min_of_right = nums1[i];
                } else { 
                    min_of_right = min(nums1[i], nums2[j]); 
                }
                // Even case
                return (max_of_left + min_of_right) / 2.0;
            }
        }
        return 0.0;
    }
};
94400