From 2ddd400611f8990cb94c62fa3184e4b93f6df598 Mon Sep 17 00:00:00 2001 From: Khalid Haider Jafri <121686427+xayyeem@users.noreply.github.com> Date: Wed, 21 Feb 2024 20:17:51 +0530 Subject: [PATCH] Create Median of Two Sorted Arrays --- Arrays/C++/Median of Two Sorted Arrays | 34 ++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Arrays/C++/Median of Two Sorted Arrays diff --git a/Arrays/C++/Median of Two Sorted Arrays b/Arrays/C++/Median of Two Sorted Arrays new file mode 100644 index 0000000..752aab9 --- /dev/null +++ b/Arrays/C++/Median of Two Sorted Arrays @@ -0,0 +1,34 @@ +Median of Two Sorted Arrays + + + +// Brute Force: + // 1.Merge Both Array + // 2.Sort them + // 3.Find Median + // TIME COMPLEXITY: O(n)+O(nlogn)+O(n) + // SPACE COMPLEXITY: O(1) + +class Solution { +public: + double findMedianSortedArrays(vector& nums1, vector& nums2) { + // Initialization some neccessary variables + vectorv; + + // store the array in the new array + for(auto num:nums1) // O(n1) + v.push_back(num); + + for(auto num:nums2) // O(n2) + v.push_back(num); + + // Sort the array to find the median + sort(v.begin(),v.end()); // O(nlogn) + + // Find the median and Return it + int n=v.size(); // O(n) + + return n%2?v[n/2]:(v[n/2-1]+v[n/2])/2.0; + } +}; +