Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create Median of Two Sorted Arrays #343

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions Arrays/C++/Median of Two Sorted Arrays
Original file line number Diff line number Diff line change
@@ -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<int>& nums1, vector<int>& nums2) {
// Initialization some neccessary variables
vector<int>v;

// 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;
}
};