LeetCode 4 Median of Two Sorted Arrays (C++, Python)
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)).
Solution C++
Solution Python
Solution C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | class Solution { private: double intFindMedianSortedArrays(vector<int>& nums1, int low1, int high1, vector<int>& nums2, int low2, int high2, int k) { if (high1 - low1 > high2 - low2) { return intFindMedianSortedArrays(nums2, low2, high2, nums1, low1, high1, k); } if (low1 > high1) { return nums2[low2 + k - 1]; } if (k == 1) { return min(nums1[low1], nums2[low2]); } int na = min(k / 2, high1 - low1 + 1); int nb = k - na; if (nums1[low1 + na - 1] > nums2[low2 + nb - 1]) { return intFindMedianSortedArrays(nums1, low1, high1, nums2, low2 + nb, high2, k - nb); } else if (nums1[low1 + na - 1] < nums2[low2 + nb - 1]) { return intFindMedianSortedArrays(nums1, low1 + na, high1, nums2, low2, high2, k - na); } else { return nums1[low1 + na - 1]; } } public: double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { const int M = nums1.size(); const int N = nums2.size(); int total = M + N; if (total % 2) { return intFindMedianSortedArrays(nums1, 0, M - 1, nums2, 0, N - 1, total / 2 + 1); } else { return (intFindMedianSortedArrays(nums1, 0, M - 1, nums2, 0, N - 1, total / 2) + intFindMedianSortedArrays(nums1, 0, M - 1, nums2, 0, N - 1, total / 2 + 1)) / 2.0; } } }; |
Solution Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | class Solution: def findKth(self, nums1, low1, high1, nums2, low2, high2, k): if high1 - low1 > high2 - low2: return self.findKth(nums2, low2, high2, nums1, low1, high1, k) if low1 > high1: return nums2[low2 + k - 1] if k == 1: return min(nums1[low1], nums2[low2]) pa = min(k / 2, high1 - low1 + 1) pb = k - pa if nums1[low1 + pa - 1] < nums2[low2 + pb - 1]: return self.findKth(nums1, low1 + pa, high1, nums2, low2, high2, k - pa) elif nums1[low1 + pa - 1] > nums2[low2 + pb - 1]: return self.findKth(nums1, low1, high1, nums2, low2 + pb, high2, k - pb) else: return nums1[low1 + pa - 1] # @param {integer[]} nums1 # @param {integer[]} nums2 # @return {float} def findMedianSortedArrays(self, nums1, nums2): M = len(nums1) N = len(nums2) if (M + N) % 2: return self.findKth(nums1, 0, M - 1, nums2, 0, N - 1, (M + N) / 2 + 1) else: return (self.findKth(nums1, 0, M - 1, nums2, 0, N - 1, (M + N) / 2) + self.findKth(nums1, 0, M - 1, nums2, 0, N - 1, (M + N) / 2 + 1)) / 2.0 |