题目:
数组A,A的长度m,数组B,B的长度n,需要找第K大的数。
要求:时间复杂度log(m+n)
思路
确定第K大的数前面的K-1个数,同时要考虑极端情况
解法
#include <iostream>
#include <vector>
using namespace std;
int findTheKthElementInTwoSortedArray01(int A[], int m, int B[], int n, int kth)
{
if (kth > (m+n)) {
return -1;
}
if(m > n) {
return findTheKthElementInTwoSortedArray01(B, n, A, m, kth);
}
if (kth == 1) {
return std::min(A[0], B[0]);
}
if (m == 0) {
return B[kth-1];
}
//分割k
int ia = std::min(kth/2, m);
int ib = kth - ia;
if (A[ia-1] < B[ib-1]) {
return findTheKthElementInTwoSortedArray01(A+ia, m-ia, B, n, kth-ia);
}
if (A[ia-1] > B[ib-1]) {
return findTheKthElementInTwoSortedArray01(A, m, B+ib, n-ib, kth-ib);
}
return A[ia-1];
}
int main()
{
vector<int> t1{1, 3, 8, 9};
vector<int> t2{};
int kth = 4;
//vector<int> t2{2, 5, 7, 15, 20};
int arr[t1.size()];
int brr[t2.size()];
std::copy(t1.begin(), t1.end(), arr);
std::copy(t2.begin(), t2.end(), brr);
int ret = findTheKthElementInTwoSortedArray01(arr, t1.size(), brr, t2.size(), kth);
cout << ret <<endl;
return 0;
}
扩展:Median of Two Sorted Arrays 两个有序数组的中位数
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
You may assume nums1 and nums2 cannot be both empty.
Example 1:
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
Example 2:
nums1 = [1, 2]
nums2 = [3, 4]
The median is (2 + 3)/2 = 2.5
寻找数组的中位数的小技巧:假设数组的长度是m,找第(m+1)/2位和第(m+2)/2位的元素,两者的平均数即为数组的中位数。