码迷,mamicode.com
首页 > 其他好文 > 详细

Median of Two Sorted Arrays

时间:2020-01-06 21:17:10      阅读:92      评论:0      收藏:0      [点我收藏+]

标签:media   n+2   ble   计算   复杂度   size   complex   描述   中位数   

描述:

  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)).You may assume nums1 and nums2 cannot be both empty.

 

解答:

  题中两个数组均为有序的数组,长度已知,查找两个数组当中的中位数。一个数组当中

中位数为,奇数的情况下为(m+n)/2,偶数的情况下为(m+n-1)/2和(m+n)/2两个数字的均值。

本题当中有一个技巧,不需要分奇数和偶数来计算中位数,奇数和偶数的中位数均为(m+n+1)/2

和(m+n+2)/2两个数字的均值。

  因此只要在两个有序的数组当中查找到这两个目标数字即可。因此问题变成了在两个有序

的数组当中查找指定数字的问题。由于复杂度的限制和数组有序的条件,因此我们考虑到使用

二分的方法来实现复杂度的需求,但是此处二分并不是对于数组,而是对于查找的序号进行二

分。

 

具体的代码如下:

class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        int m=nums1.size(),n=nums2.size();
        int left=(m+n+1)/2,right=(m+n+2)/2;
        return (findKth(nums1,0,nums2,0,left)+findKth(nums1,0,nums2,0,right))/2.0;
    }

    //在两个有序的数组当中查找第k个数字,二分查找,是对查找的序号进行二分
    int findKth(vector<int>& nums1, int i, vector<int>& nums2, int j, int k) {
     //边界条件1,目前所处的位置超出了数组的长度
if (i >= nums1.size()) return nums2[j + k - 1]; if (j >= nums2.size()) return nums1[i + k - 1];
     //边界条件2,查找的长度为1.同时这也为递归基,因为无论长度为奇数还是偶数,最终都会变为1
if (k == 1) return min(nums1[i], nums2[j]);
     //两个有序数组当中的k/2位置的值,较小的那个包含的k/2个数字当中一定不含目标数字
int midVal1 = (i + k / 2 - 1 < nums1.size()) ? nums1[i + k / 2 - 1] : INT_MAX; int midVal2 = (j + k / 2 - 1 < nums2.size()) ? nums2[j + k / 2 - 1] : INT_MAX;
     //每一次可以去除掉k/2个数字
if (midVal1 < midVal2) { return findKth(nums1, i + k / 2, nums2, j, k - k / 2); } else { return fidKth(nums1, i, nums2, j + k / 2, k - k / 2); }a } };

Median of Two Sorted Arrays

标签:media   n+2   ble   计算   复杂度   size   complex   描述   中位数   

原文地址:https://www.cnblogs.com/wangkaia/p/12158390.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!