寻找两个正序数组的中位数(C语言)

题目:给定两个大小分别为m和n的正序(从小到大)数组nums1和nums2。请你找出并返回这两个正序数组的中位数。


解决这个问题,一种思想是首先将两个数组合并后排序,直接找到中位数。这种方法的复杂度关键在于排序,可以实现O(log(m+n))的复杂度。

另一种想法就是同时遍历两个数组,遍历到中位数位置时,即可得到中位数。

1. 当m+n为偶数:中位数是遍历的第(len1+len2)/2个数与第(len1+len2)/2+1个数的平均值。

2. 当m+n为奇数:中位数是遍历的第(len1+len2)/2+1个数。

代码如下:

float findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size){
    int i=0, head1=0, head2=0, tmp[] = {0, 0}, thres;
    thres = (nums1Size+nums2Size)/2;
	for(i=0;i<thres+1;i++){
		if(nums1Size==0||nums1Size==head1){
			if(i>=thres-1){
				tmp[0]=tmp[1];
				tmp[1]=nums2[head2];
			}
			head2++;
		}
		else if(nums2Size==0||nums2Size==head2){ 	
			if(i>=thres-1){
				tmp[0]=tmp[1];
				tmp[1]=nums1[head1];
			}
			head1++;
		}
		else{
			if(nums1[head1]>nums2[head2]){
				if(i>=thres-1){
                    tmp[0]=tmp[1];
                    tmp[1]=nums2[head2];
			    }
				head2++;
			}
			else if(nums1[head1]<=nums2[head2]){
				if(i>=thres-1){
					tmp[0]=tmp[1];
					tmp[1]=nums1[head1];
				}
				head1++;
			}
		}
	}
	if((nums1Size+nums2Size)%2==0) return (float)(tmp[0]+tmp[1])/2;
	else return (float)tmp[1];
}


版权声明:本文为diqiudq原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。