class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int len1 = nums1.size();
int len2 = nums2.size();
int mid = (len1 + len2) / 2;
bool odd = (len1 + len2) % 2 != 0;//奇数
mid = odd ? mid++ : mid;
if (len1 == 0 || len2 == 0) {
vector<int>& nums = len1 == 0 ? nums2 : nums1;
return odd? nums[mid]: (nums[mid-1]+(nums[mid]))/2.0 ;
}
int i1 = 0;
int i2 = 0;
int last = nums1[i1] <= nums2[i2]? nums1[i1]: nums2[i2];
// 1 3 5 7 9 10; 2 4 6 8
for (;;) {
//移动
//vector<int>* pTarget = nullptr;
if (nums1[i1] < nums2[i2]) {
last = nums1[i1++];
}
else {
last = nums2[i2++];
}
if ((i1 == len1) || (i2 == len2)) {
vector<int>* pTarget = nullptr;
int index;
if (i1 == len1) {
pTarget = &nums2;
index = mid - (i1);
}
else {
pTarget = &nums1;
index = mid - (i2);
}
last = (index == 0 || last > (*pTarget)[index - 1]) ? last : (*pTarget)[index - 1];
return odd ? (*pTarget)[index] : (last + (*pTarget)[index]) / 2.0;
}
//终结
if (i1+i2 == mid) {
int cur = nums1[i1] < nums2[i2] ? nums1[i1] : nums2[i2];
if (odd) {
return cur;
}
else {
return (last + cur) / 2.0;
}
}
}
return 0.0;
}
};
代码有点难懂。效率还好。