From 66ab312f9ad615b91c4392e312d4ad414b811c06 Mon Sep 17 00:00:00 2001 From: huihut Date: Fri, 9 Feb 2018 22:46:47 +0800 Subject: [PATCH] Solve 4. Median of Two Sorted Arrays --- .../median-of-two-sorted-arrays.h | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/Problems/LeetcodeProblems/median-of-two-sorted-arrays.h b/Problems/LeetcodeProblems/median-of-two-sorted-arrays.h index e69de29..3ad5a44 100644 --- a/Problems/LeetcodeProblems/median-of-two-sorted-arrays.h +++ b/Problems/LeetcodeProblems/median-of-two-sorted-arrays.h @@ -0,0 +1,33 @@ +class Solution { +public: + double findMedianSortedArrays(vector& nums1, vector& nums2) { + int len1 = nums1.size(); + int len2 = nums2.size(); + int len = len1 + len2; + if(len & 1) + return findKth(nums1, 0, nums2, 0, len / 2 + 1); + else + return (findKth(nums1, 0, nums2, 0, len / 2) + findKth(nums1, 0, nums2, 0, len / 2 + 1)) / 2; + } + + double findKth(vector& nums1, int i1, vector& nums2, int i2, int k) { + if (i1 >= nums1.size()) { + return nums2[i2 + k - 1]; + } + if (i2 >= nums2.size()) { + return nums1[i1 + k - 1]; + } + if (k == 1) { + return min(nums1[i1], nums2[i2]); + } + int key1 = i1 + k / 2 - 1 >= nums1.size() ? INT_MAX : nums1[i1 + k / 2 - 1]; + int key2 = i2 + k / 2 - 1 >= nums2.size() ? INT_MAX : nums2[i2 + k / 2 - 1]; + if (key1