<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) {
        if (nums2.size() < nums1.size())
            swap(nums1, nums2);

        int total = nums1.size() + nums2.size();
        int half = total / 2;
        int left = 0;
        int right = nums1.size() - 1;

        while (true)
        {
            int mid1 = right >= 0 ? (left + right) / 2 : -1;    // to let mid1 can be -1
            int mid2 = (half) - (mid1 + 1) - 1;

            int val1_left = mid1 >= 0 ? nums1[mid1] : INT_MIN;
            int val1_right = mid1 + 1 < nums1.size() ? nums1[mid1+1] : INT_MAX;
            int val2_left = mid2 >= 0 ? nums2[mid2] : INT_MIN;
            int val2_right = mid2 + 1 < nums2.size() ? nums2[mid2+1] : INT_MAX;

            if (val1_left <= val2_right && val2_left <= val1_right)
                if (total % 2)
                    return min(val1_right, val2_right);
                else
                    return (min(val1_right, val2_right) + max(val1_left, val2_left)) / 2.0;
            
            else if (val1_left > val2_right)
            {
                right = mid1 - 1;
            }
            else
                left = mid1 + 1;
        }
        return -1;
    }
};
94700