<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>& a, vector<int>& b) {
        int n1 = a.size();
        int n2 = b.size();
        
        // Ensure that the first array is the smaller one
        if (n1 > n2) return findMedianSortedArrays(b, a);
        
        int low = 0, high = n1;
        int left = (n1 + n2 + 1) / 2; // Target partition position
        
        while (low <= high) {
            int mid1 = (low + high) >> 1; // mid1 is the partition index in 'a'
            int mid2 = left - mid1;       // mid2 is the partition index in 'b'
            
            int l1 = (mid1 == 0) ? INT_MIN : a[mid1 - 1]; // Left max of 'a'
            int l2 = (mid2 == 0) ? INT_MIN : b[mid2 - 1]; // Left max of 'b'
            int r1 = (mid1 == n1) ? INT_MAX : a[mid1];    // Right min of 'a'
            int r2 = (mid2 == n2) ? INT_MAX : b[mid2];    // Right min of 'b'
            
            if (l1 <= r2 && l2 <= r1) { // Correct partition found
                if ((n1 + n2) % 2 == 0) // Even total length
                    return (max(l1, l2) + min(r1, r2)) / 2.0;
                else // Odd total length
                    return max(l1, l2);
            } else if (l1 > r2) { // 'a' partition is too far right
                high = mid1 - 1;
            } else { // 'a' partition is too far left
                low = mid1 + 1;
            }
        }
        
        // This point should not be reached if the input arrays are valid
        throw invalid_argument("Input arrays are not sorted correctly.");
    }
};

94400