Description:
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
Example 1:
nums1 = [1, 3] nums2 = [2] The median is 2.0
Example 2:
nums1 = [1, 2] nums2 = [3, 4] The median is (2 + 3)/2 = 2.5
Solution:
#include <stdio.h>
#include <stdlib.h>
double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size) {
int num3[nums1Size+nums2Size]; //申请全新数组
int i=0;
int j=0;
int k=0;
while(i<nums1Size&&j<nums2Size){
if(nums1[i]<nums2[j]){
num3[k]=nums1[i];
i++;
k++;
}
else if(nums2[j]<nums1[i]){
num3[k]=nums2[j];
j++;
k++;
}
else{
num3[k]=nums1[i];
num3[k+1]=nums2[j];
k=k+2;
i++;
j++;
}
}
while(i<nums1Size){
num3[k]=nums1[i];
i++;
k++;
}
while(j<nums2Size){
num3[k]=nums2[j];
j++;
k++;
}
if((nums1Size+nums2Size)%2==0){ //k为偶数
int m,n;
m=(nums1Size+nums2Size)/2;
n=m-1;
return (((double)(num3[m]+num3[n]))/2);
}
else{
int m;
m=(nums1Size+nums2Size)/2;
return (double)(num3[m]);
}
}
int main(){
int a[]={1,2};
int b[]={3,4};
printf("median is %.1f",findMedianSortedArrays(a,2,b,2));
return 0;
}
Idea:1.申请新的数组num3保存排序后的值;2.由于num1和num2的数组长度可能不一,因此在遍历两个数组时需要考虑边界情况,比如num1遍历完成,num2还有值反之一样;3.取中指时需要考虑num3元素个数为奇数还是偶数
Summary:printf("median is %.1f")格式化输出小数点后一位浮点数