From 28822cd78d170040126329965f9fc2faba6fd35a Mon Sep 17 00:00:00 2001 From: KongJHong Date: Sat, 20 Oct 2018 14:53:28 +0800 Subject: [PATCH 1/2] cpp solution --- .../Solution.cpp | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 solution/004.Median of Two Sorted Arrays/Solution.cpp diff --git a/solution/004.Median of Two Sorted Arrays/Solution.cpp b/solution/004.Median of Two Sorted Arrays/Solution.cpp new file mode 100644 index 0000000000000..964706f362b5d --- /dev/null +++ b/solution/004.Median of Two Sorted Arrays/Solution.cpp @@ -0,0 +1,35 @@ +class Solution { +public: + double findMedianSortedArrays(vector& nums1, vector& nums2) { + int nums[10000] = { 0 }; + int index = 0; + vector::iterator it1 = nums1.begin(); + vector::iterator it2 = nums2.begin(); + for (; it1 != nums1.end() && it2 != nums2.end();) { + if (*it1 >= *it2) { + nums[index++] = *it2; + it2++; + } + else { + nums[index++] = *it1; + it1++; + } + } + while (it1 != nums1.end()) { + nums[index++] = *it1; + it1++; + } + while (it2 != nums2.end()) { + nums[index++] = *it2; + it2++; + } + + if (index % 2 == 0) { + return (double)((nums[index/2] + nums[index/2 - 1])/2.0); + } + else { + return (double)(nums[index/2]); + } + + } +}; \ No newline at end of file From 80adad0daad9502b1fc15aa0f789eccb11e7143e Mon Sep 17 00:00:00 2001 From: KongJHong Date: Sat, 20 Oct 2018 14:54:53 +0800 Subject: [PATCH 2/2] Add solution 004[CPP] --- solution/004.Median of Two Sorted Arrays/Solution.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/solution/004.Median of Two Sorted Arrays/Solution.cpp b/solution/004.Median of Two Sorted Arrays/Solution.cpp index 964706f362b5d..2496313fa0f94 100644 --- a/solution/004.Median of Two Sorted Arrays/Solution.cpp +++ b/solution/004.Median of Two Sorted Arrays/Solution.cpp @@ -15,6 +15,7 @@ class Solution { it1++; } } + while (it1 != nums1.end()) { nums[index++] = *it1; it1++;