class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int size1 = nums1.size();
int size2 = nums2.size();
int index1 = 0, index2 = 0;
vector<int> v;
while (index1 < size1 && index2 < size2)
{
if (nums1[index1] < nums2[index2])
{
v.push_back(nums1[index1]);
index1++;
}
else if (nums1[index1] > nums2[index2])
{
v.push_back(nums2[index2]);
index2++;
}
else
{
v.push_back(nums1[index1]);
v.push_back(nums2[index2]);
index1++;
index2++;
}
}
while (index1 < size1)
{
v.push_back(nums1[index1]);
index1++;
}
while (index2 < size2)
{
v.push_back(nums2[index2]);
index2++;
}
return ((size1 + size2) % 2 == 0) ? (double)(v[(size1 + size2 - 1)/2] + v[(size1 + size2 - 1)/2 + 1])/2 : v[(size1 + size2)/2];
}
}
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int total = nums1.size() + nums2.size();
if (total & 0x1)
{
return findKth(nums1, 0, nums2, 0, total / 2 + 1);
}
else
return (findKth(nums1, 0, nums2, 0, total / 2)
+ findKth(nums1, 0, nums2, 0, total / 2 + 1)) / 2;
}
private:
double findKth(vector<int>& a, int idx1, vector<int>& b, int idx2, int k)
{
int m = a.size() - idx1;
int n = b.size() - idx2;
if (m > n) {
return findKth(b, idx2, a, idx1, k);
}
if (m == 0) {
return b[k - 1];
}
if (k == 1) {
return min(a[idx1], b[idx2]);
}
//divide k into two parts
int pa = min(k / 2, m), pb = k - pa;
if (a[idx1 + pa - 1] < b[idx2 + pb - 1]) {
return findKth(a, idx1 + pa, b, idx2, k - pa);
}
else if (a[idx1 + pa - 1] > b[idx2 + pb - 1]) {
return findKth(a, idx1, b, idx2 + pb, k - pb);
}
else {
return a[pa - 1];
}
}
};