<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) {
        int n = nums1.size();
        int m = nums2.size();
        vector<int> a = FindUnion(nums1, nums2, n, m);
        int k = a.size();
        if (k == 0) return 0.0;  // No elements case
        if (k == 1) return a[0]; // Single element case
        
        // If the merged array size is odd
        if (k % 2 == 1) {
            return a[k / 2];  // Middle element
        } else {
            // If the merged array size is even
            return (static_cast<double>(a[k / 2]) + a[(k / 2) - 1]) / 2.0;
        }
    }

    vector<int> FindUnion(vector<int>& arr1, vector<int>& arr2, int n, int m) {
        int i = 0, j = 0;  // pointers for arr1 and arr2
        vector<int> Union; // Union vector to store merged elements

        // Merging both arrays
        while (i < n && j < m) {
            if (arr1[i] <= arr2[j]) {
                Union.push_back(arr1[i]);
                i++;
            } else {
                Union.push_back(arr2[j]);
                j++;
            }
        }

        // Add remaining elements from arr1, if any
        while (i < n) {
            Union.push_back(arr1[i]);
            i++;
        }

        // Add remaining elements from arr2, if any
        while (j < m) {
            Union.push_back(arr2[j]);
            j++;
        }

        return Union;
    }
};
95600