leetcode学习笔记-4.寻找两个正序数组的中位数
思路:已知数组大小为n,当n为偶数,中位数下标为n/2-1和n/2。因此只需找到两个数组第n/2-1和n/2大的数即可。
当n为奇数,中位数下标为(n-1)/2。因此只需找到两个数组第(n-1)/2大的数即可。`
设置两个指针,进行比较,小的那个后移,同时设置一个计数器计算下标。犯过的一个错误是没有考虑数组到头的情况。
double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size){
int s1=0,s2=0,n=nums1Size+nums2Size,flag;//n为两个数组总大小,s1,s2为两个数组的指针
double s=0;
if(n%2==0)
flag=n/2+1;
else
flag=(n-1)/2+1;//flag为需要找到第flag-1小的数
for(int counter=0;counter<flag;counter++){//counter计数合成的数组的下标
//数组1到头的情况
if(s1==nums1Size){
if(n%2==0){//总数为偶
if(counter==flag-1 ||counter==flag-2){//如果到达下标为n/2-1和n/2位置就写入s
s+=nums2[s2];
}
}
else{//总数为奇数
if(counter==flag-1){
s+=nums2[s2];//如果到达下标为(n-1)/2位置就写入s
}
}
s2++;
}
//数组2到头的情况
else if(s2==nums2Size){
if(n%2==0){
if(counter==flag-1 ||counter==flag-2){
s+=nums1[s1];
}
}
else{
if(counter==flag-1){
s+=nums1[s1];
}
}
s1++;
}
//数组都未到头
else{
if(nums1[s1]>=nums2[s2]){
if(n%2==0){
if(counter==flag-1 ||counter==flag-2){
s+=nums2[s2];
}
}
else{
if(counter==flag-1){
s+=nums2[s2];
}
}
s2++;
}//如果数组1当前数字大于数组2,数组2指针后移,如果counter到达目标值就更新s
else{
if(n%2==0){
if(counter==flag-1 ||counter==flag-2){
s+=nums1[s1];
}
}
else{
if(counter==flag-1){
s+=nums1[s1];
}
}
s1++;
}
}
}
if(n%2==0)//偶数返回两数之和的二分之一
return s/2;
else//奇数直接返回s
return s;
}