在2个排序数组内找到第K小的元素

来源:互联网 发布:linux文件系统目录结构 编辑:程序博客网 时间:2024/05/17 22:42
/*Find the k-th Smallest Element in the Union of Two Sorted Arrays*/#include <iostream>int findKth(int a[], int m, int b[], int n, int k){int pa = m / (m + n) * k;int pb = k - pa - 1;int a_pa_1 = (pa == 0) ? INT_MIN : a[pa - 1];int b_pb_1 = (pb == 0) ? INT_MIN : b[pb - 1];int a_pa = (pa == m) ? INT_MAX : a[pa];int b_pb = (pb == n) ? INT_MAX : b[pb];if(a_pa > b_pb && a_pa_1 < b_pb) return b_pb;if(b_pb > a_pa && b_pb_1 < a_pa) return a_pa;if(a_pa > b_pb){return findKth(a, pa, b + pb + 1, n - pb - 1, k - pb - 1);}else{return findKth(a + pa + 1, m - pa - 1, b, pb, k - pa - 1);}};int main(){    int A[] = {1, 8, 8, 10, 20};      int B[] = {5, 8, 8, 9, 22, 110};                int k = 7;  int res = findKth(A, 5, B, 6, k);return 0;}

原创粉丝点击