题目描述

给定两个大小分别为 m 和 n 的正序(从小到大)数组 nums1 和 nums2。请你找出并返回这两个正序数组的 中位数 。要求O(lgn)的时间复杂度

链接:https://leetcode-cn.com/problems/median-of-two-sorted-arrays

示例1

  1. 输入:nums1 = [1,2], nums2 = [3,4]
  2. 输出:2.50000
  3. 解释:合并数组 = [1,2,3,4] ,中位数 (2 + 3) / 2 = 2.5

示例2

  1. 输入:nums1 = [0,0], nums2 = [0,0]
  2. 输出:0.00000

解题思路

详见该题解,写的十分透彻,根据该题解得到的代码如下:

  1. class Solution {
  2. public:
  3. int binary_find(vector<int>& nums1, vector<int>& nums2, int start1, int start2, int count) {
  4. int end1 = nums1.size()-1, end2 = nums2.size()-1;
  5. //确保nums1可用的长度一定小于nums2
  6. if (end1-start1 > end2-start2)
  7. return binary_find(nums2, nums1, start2, start1, count);
  8. //先进行该判断:当nums1目前没有可用的数时,说明可以直接返回nums2的数
  9. if (end1-start1+1 == 0)
  10. return nums2[start2+count-1];
  11. //由于可能存在start1+1越界的情况,所以后进行该判断:当只用比较一个数时,比较完可以直接返回
  12. if (count==1)
  13. //注意是返回最小值而不是最大值
  14. return min(nums1[start1], nums2[start2]);
  15. int i = start1 + min(end1-start1+1, count / 2) - 1;
  16. int j = start2 + min(end2-start2+1, count / 2) - 1;
  17. if (nums1[i] > nums2[j])
  18. return binary_find(nums1, nums2, start1, j+1, count-(j-start2+1));
  19. else
  20. return binary_find(nums1, nums2, i+1, start2, count-(i-start1+1));
  21. }
  22. double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
  23. int len1 = nums1.size(), len2 = nums2.size();
  24. if ((len1+len2)%2)
  25. return binary_find(nums1, nums2, 0, 0, (len1+len2+1)/2);
  26. else {
  27. int ret1 = binary_find(nums1, nums2, 0, 0, (len1+len2+1)/2);
  28. int ret2 = binary_find(nums1, nums2, 0, 0, (len1+len2+2)/2);
  29. return (float)(ret1+ret2) / 2.;
  30. }
  31. }
  32. };