classSolution { public: doublefindMedianSortedArrays(vector<int>& nums1, vector<int>& nums2){ int m = nums1.size(); int n = nums2.size(); if (m > n) { vector<int> temp = nums1; nums1 = nums2; nums2 = temp; int tmp = m; m = n; n = tmp; } int iMin = 0, iMax = m, halfLen = (m + n + 1) / 2; while (iMin <= iMax) { int i = (iMin + iMax) / 2; int j = halfLen - i; if (i < iMax && nums2[j-1] > nums1[i]){ iMin = iMin + 1; // i is too small } elseif (i > iMin && nums1[i-1] > nums2[j]) { iMax = iMax - 1; // i is too big } else { // i is perfect int maxLeft = 0; if (i == 0) { maxLeft = nums2[j-1]; } elseif (j == 0) { maxLeft = nums1[i-1]; } else { maxLeft = max(nums1[i-1], nums2[j-1]); } if ( (m + n) % 2 == 1 ) { return maxLeft; }
int minRight = 0; if (i == m) { minRight = nums2[j]; } elseif (j == n) { minRight = nums1[i]; } else { minRight = min(nums2[j], nums1[i]); }