数组类题目总结---两个数组的中位数

数组类题目总结---两个数组的中位数_第1张图片

/******************************************************************************

Welcome to GDB Online.
GDB online is an online compiler and debugger tool for C, C++, Python, PHP, Ruby, 
C#, VB, Perl, Swift, Prolog, Javascript, Pascal, HTML, CSS, JS
Code, Compile, Run and Debug online from anywhere in world.

*******************************************************************************/
#include 
#include 
#include 
using namespace std;
int getKth(vector nums1, vectornums2, int k) {
    int index1 = 0;
    int index2 = 0;
    int lenght1 = nums1.size();
    int lenght2 = nums2.size();
    while(1) {
        if(index1 == nums1.size()) {
            return nums2[index2 + k - 1];
        }
        if (index2 == nums2.size()) {
            return nums1[index1 + k - 1];
        }
        if (k == 1) {
            return min(nums1[index1], nums2[index2]);
        }
        
        int mid1 = min(index1 + k / 2 - 1, lenght1 - 1);
        int mid2 = min(index2 + k / 2 - 1, lenght2 - 1);
        if (nums1[mid1] < nums2[mid2]) {
            k -= (mid1 - index1 + 1);
            index1 = mid1 + 1;
        } else {
            k -= (mid2 - index2 + 1);
            index2 = mid2 + 1;
        }
    }
}
int main()
{
    vector nums1 = {1, 3, 5};
    vector nums2 = {2, 4, 6};
    int sum_size = nums1.size() + nums2.size();
    if (sum_size % 2 == 1) {
        std::cout << getKth(nums1, nums2, (sum_size + 1) / 2) << endl;
    } else {
        std::cout <<  (getKth(nums1, nums2, (sum_size) / 2) + getKth(nums1, nums2, (sum_size / 2 + 1))) / 2.0;
        std::cout << endl;
    }
    return 0;
}

你可能感兴趣的:(算法)