19.1.19 [LeetCode4]Median of Two Sorted Arrays

Posted TobicYAL

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了19.1.19 [LeetCode4]Median of Two Sorted Arrays相关的知识,希望对你有一定的参考价值。

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.

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
技术分享图片
 1 class Solution {
 2 public:
 3     double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
 4         int m = nums1.size(), n = nums2.size();
 5         int idx1 = (m + n + 1) / 2, idx2 = (m + n + 2) / 2;
 6         return (findkth(nums1, 0, nums2, 0, idx1) + findkth(nums1, 0, nums2, 0, idx2)) / 2.0;
 7     }
 8     int findkth(vector<int>&nums1, int i, vector<int>&nums2, int j, int k) {
 9         if (i >= nums1.size())return nums2[j + k - 1];
10         if (j >= nums2.size())return nums1[i + k - 1];
11         if (k == 1)return min(nums1[i], nums2[j]);
12         int midval1 = (i + k / 2 <= nums1.size()) ? nums1[i + k / 2 - 1] : 9999999;
13         int midval2 = (j + k / 2 <= nums2.size()) ? nums2[j + k / 2 - 1] : 9999999;
14         if (midval1 < midval2)
15             return findkth(nums1, i + k / 2, nums2, j, k - k / 2);
16         return findkth(nums1, i, nums2, j + k / 2, k - k / 2);
17     }
18 };
View Code

有几个点:

1.求中位数是求整个数组的第 (m+n+1)/2 和 (m+n+2)/2 个数的平均值

2.使用奇妙的递归二分查找两个数组中的第k大数

3.注意数组边界判断

以上是关于19.1.19 [LeetCode4]Median of Two Sorted Arrays的主要内容,如果未能解决你的问题,请参考以下文章

leetcode4 median Of two sorted array

leetcode4. Median of Two Sorted Arrays

LeetCode4 :median of two sorted arrays---求两个有序数组的中位数

LeetCode4. Median of Two Sorted Arrays---vector实现O(log(m+n)--- findkth

LeetCode4:两个排序数组的中位数

Leetcode4. 寻找两个正序数组的中位数(二分)