class Solution {
public:
/**
* find median in two sorted array
* @param arr1 int整型vector the array1
* @param arr2 int整型vector the array2
* @return int整型
*/
int findMedianinTwoSortedAray(vector<int>& arr1, vector<int>& arr2) {
// write code here
if(arr1.size() == 1) return min(arr1[0],arr2[0]);///特判
int n = arr1.size();///数组长度
int l1 = 0,r1 = n -1 ,l2 = 0,r2 = n -1;///初始指针
///元素个数位奇数,flag = 1,为偶数flag =0
int flag = ((r1 - l1 + 1) & 1);
while(l1 < r1){</int></int>
int mid1 = l1 + ((r1 - l1) >> 1); int mid2 = l2 + ((r2 - l2) >> 1); ///更新区域的个数,奇数,flag = 1,为偶数flag =0 flag = ((r1 - l1 + 1) & 1); ///若两数组中位数相等,整体的中位数也是这个 if(arr1[mid1] == arr2[mid2]) return arr1[mid1]; else if(arr1[mid1] > arr2[mid2]){ ///如果区域个数是奇数 if(flag){ r1 = mid1; l2 = mid2; }else{ ///如果区域个数是偶数 r1 = mid1; l2 = mid2 + 1; } }else{ ///如果区域个数是奇数 if(flag){ l1 = mid1; r2 = mid2; }else{ ///如果区域个数是偶数 l1 = mid1 + 1; r2 = mid2; } } } return min(arr1[l1],arr2[l2]); }
};