# 4. Median of Two Sorted Arrays

4. Median of Two Sorted Arrays

class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int sz = nums1.size() + nums2.size();
int i, j, k;
i = j = k = 0;
double sum = 0;
while(i < nums1.size() && j < nums2.size()){
bool f;
if(nums1[i] < nums2[j]){
i++;
f = false;
}
else{
j++;
f = true;
}
k++;
if(k == (sz - 1) / 2 + 1){
if(f)   sum += nums2[j-1];
else    sum += nums1[i-1];
}
else if(k == (sz - 1) / 2 + 2){
if(sz % 2 == 0){
if(f)   sum += nums2[j-1];
else    sum += nums1[i-1];
sum /= 2;
}
break;
}
else if(k > (sz - 1) / 2 + 2){
break;
}
}
while(i < nums1.size()){
i++;
k++;
if(k == (sz - 1) / 2 + 1){
sum += nums1[i-1];
}
else if(k == (sz - 1) / 2 + 2){
if(sz % 2 == 0){
sum += nums1[i-1];
sum /= 2;
}
break;
}
else if(k > (sz - 1) / 2 + 2){
break;
}
}
while(j < nums2.size()){
j++;
k++;
if(k == (sz - 1) / 2 + 1){
sum += nums2[j-1];
}
else if(k == (sz - 1) / 2 + 2){
if(sz % 2 == 0){
sum += nums2[j-1];
sum /= 2;
}
break;
}
else if(k > (sz - 1) / 2 + 2){
break;
}
}
return sum;
}
};

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客