寻找2个有序数组的中位数
[4. 寻找两个正序数组的中位数 - 力扣(LeetCode)][https://leetcode.cn/problems/median-of-two-sorted-arrays/]
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int p1 = 0;
int p2 = 0;
int p3 = 0;
int num1 = 0;
int num2 = 0;
if(nums1.size()==0&&nums2.size()==0) return 0;
if(nums1.size()==1&&nums2.size()==1) return(double)(nums1[0]+nums2[0])/2;
if(nums2.size()==0) {
if(nums1.size()%2){
return nums1[nums1.size()/2];
}
else return (double)(nums1[nums1.size()/2]+nums1[nums1.size()/2-1])/2;
}
if(nums1.size()==0) {
if(nums2.size()%2){
return nums2[nums2.size()/2];
}
else return (double)( nums2[nums2.size()/2]+nums2[nums2.size()/2-1])/2;
}
p3 = (nums1.size() + nums2.size()) / 2;
while (p3 >=0) {
if (nums1[p1] > nums2[p2]) {
--p3;
if (p3 == 0) {
num1 = nums2[p2];
}
if (p3 == -1) {
num2 = nums2[p2];
break;
}
if (p2 < nums2.size() - 1) ++p2;
else break;
}
else if (nums1[p1] <= nums2[p2]) {
--p3;
if (p3 == 0) {
num1 = nums1[p1];
}
if (p3 == -1) {
num2 = nums1[p1];
break;
}
if (p1 < nums1.size() - 1) ++p1;
else break;
}
}
if (p1 == nums1.size() - 1&&p3>=0) {
if (p3 > 0) {
num1 = nums2[p2 + p3 - 1];
num2 = nums2[p2 + p3];
}
else num2 = nums2[p2];
}
else if (p2 == nums2.size() - 1 && p3 >=0 ) {
if (p3 > 0) {
num1 = nums1[p1 + p3 - 1];
num2 = nums1[p1 + p3];
}
else num2 = nums1[p1];
}
if ((nums1.size() + nums2.size()) % 2) num1 = num2;
return (double)(num1 + num2) / 2;
}
标签:p2,p3,num2,中位数,解法,数组,nums1,nums2,size
From: https://www.cnblogs.com/chunbai11/p/16754323.html