first commit
This commit is contained in:
@@ -0,0 +1,79 @@
|
||||
// MedianOfSortedArrays.cpp : This file contains the 'main' function. Program execution begins and ends there.
|
||||
//
|
||||
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
|
||||
using namespace std;
|
||||
|
||||
class Solution {
|
||||
public:
|
||||
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2)
|
||||
{
|
||||
vector<int> combined;
|
||||
combined.resize(nums1.size() + nums2.size());
|
||||
|
||||
size_t i = 0, j = 0;
|
||||
size_t index = 0, max = nums1.size() + nums2.size();
|
||||
|
||||
for (; i < nums1.size() && j < nums2.size(); )
|
||||
{
|
||||
if (nums1[i] < nums2[j])
|
||||
{
|
||||
combined[index] = nums1[i];
|
||||
index++, i++;
|
||||
}
|
||||
else
|
||||
{
|
||||
combined[index] = nums2[j];
|
||||
index++, j++;
|
||||
}
|
||||
}
|
||||
|
||||
for (; i < nums1.size(); i++)
|
||||
{
|
||||
combined[index] = nums1[i];
|
||||
index++;
|
||||
}
|
||||
for (; j < nums2.size(); j++)
|
||||
{
|
||||
combined[index] = nums2[j];
|
||||
index++;
|
||||
}
|
||||
|
||||
double median;
|
||||
size_t size = combined.size();
|
||||
if (combined.size() % 2 == 0)
|
||||
{
|
||||
median = (combined[size / 2 - 1] + combined[size / 2]) / 2.0f;
|
||||
}
|
||||
else
|
||||
{
|
||||
median = combined[size / 2];
|
||||
}
|
||||
|
||||
return median;
|
||||
}
|
||||
};
|
||||
|
||||
int main()
|
||||
{
|
||||
vector<int> s1{ 1,2 };
|
||||
vector<int> s2{ 3,4};
|
||||
Solution s;
|
||||
|
||||
cout << s.findMedianSortedArrays(s1, s2) << endl;
|
||||
|
||||
|
||||
}
|
||||
|
||||
// Run program: Ctrl + F5 or Debug > Start Without Debugging menu
|
||||
// Debug program: F5 or Debug > Start Debugging menu
|
||||
|
||||
// Tips for Getting Started:
|
||||
// 1. Use the Solution Explorer window to add/manage files
|
||||
// 2. Use the Team Explorer window to connect to source control
|
||||
// 3. Use the Output window to see build output and other messages
|
||||
// 4. Use the Error List window to view errors
|
||||
// 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project
|
||||
// 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
|
||||
Reference in New Issue
Block a user