1. 程式人生 > >19.1.19 [LeetCode4]Median of Two Sorted Arrays

19.1.19 [LeetCode4]Median of Two Sorted Arrays

idv leet open ray 遞歸 closed cto show alt

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