Leetcode 4. Median of Two Sorted Arrays

该博客讨论了一个算法问题,即如何在O(log(M+N))的时间复杂度内找到两个已排序数组的中位数。提供的解决方案是通过合并两个数组并找到中间元素,考虑数组长度为奇数和偶数的情况。此问题考察了数组操作和中位数计算的效率。
本文首发于每日一题:4 - 咸鱼Blog

Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.

The overall run time complexity should be O(log (m+n)).

Example 1

 Input: nums1 = [1,3], nums2 = [2]
 Output: 2.00000
 Explanation: merged array = [1,2,3] and median is 2.

Example 2

 Input: nums1 = [1,2], nums2 = [3,4]
 Output: 2.50000
 Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.

Constraints

  • nums1.legnth == m

  • nums2.legnth == n

  • 0 <= m <=1000

  • 0 <= n <= 1000

  • 1 <= m+n <= 2000

  • -10^6 <= nums1[i], nums2[i] <= 10^6

Solution code

 
double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size){
     int sum=nums2Size+nums1Size;
     int nums3[MAX+MAX]={0};
     int re=sum%2;
     int index=0;
     int a1=0,a2=0;
     while(a1<nums1Size&&a2<nums2Size){
         if(nums1[a1]<nums2[a2])nums3[index++]=nums1[a1++];
         else(nums1[a1]>nums2[a2])nums3[index++]=nums2[a2++];
     }
     while(a1<nums1Size)nums3[index++]=nums1[a1++];
     while(a2<nums2Size)nums3[index++]=nums2[a2++];
     if(re){
         index=(sum-re)/2;
         return (double)nums3[index];
     }
     else{
         index=sum/2;
         return ((double)nums3[index]+(double)nums3[index-1])/2.0;
     }
 }

Note:

  1. 这题需要寻找中位数,要求的时间复杂度为O(log(M+N),相当于将两个给定的数组遍历一遍;

  2. 可以真正生成一个新数组,是两个数组的归并,像上面代码示例,也可以标记的形式,获取对应数字即可,在源代码中有;

  3. 只需要针对大小进行指针的前进选择,到达对应位置即可找到;

  4. 需要分奇数偶数进行输出;

  5. 输出结果是五位小数的double

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值