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.注意数组边界判断

posted @ 2019-01-19 11:44  TobicYAL  阅读(159)  评论(0编辑  收藏  举报