leetcode Median of Two Sorted Arrays (C)

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")格式化输出小数点后一位浮点数



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值