classSolution { public: intgetKthElement(const vector<int> &nums1, const vector<int> &nums2, int k) { /* * Main idea:To find the k (k>1) smallest element,then take * pivot1 = nums1[k/2-1] and pivot2 = nums2[k/2-1] for comparison * Here "/" denotes integer division * nums1 less than or equal to pivot1 the elements that are nums1[0 .. k/2-2] total k/2-1 elements * nums2 less than or equal to pivot2 the elements that are nums2[0 .. k/2-2] total k/2-1 elements * take pivot = min(pivot1, pivot2),in the two arrays, less than or equal to pivot the elements * total will not exceed (k/2-1) + (k/2-1) <= k-2 elements * thus pivot itself can only be at most the k-1 smallest element * if pivot = pivot1,then nums1[0 .. k/2-1] cannot be the k smallest element。 * take all these elements "delete",the remaining as new nums1 array * if pivot = pivot2,then nums2[0 .. k/2-1] cannot be the k smallest element。 * take all these elements "delete",the remaining as new nums2 array * since we "delete" some elements(these elements are all smaller than the k smaller element),therefore need to * modify k the value of,subtract the number of deleted elements */
int m = nums1.size(); int n = nums2.size(); int idx1 = 0, idx2 = 0; int new_idx1, new_idx2, pivot1, pivot2;
while (true) { // boundary case if (idx1 == m) return nums2[idx2 + k - 1];
if (idx2 == n) return nums1[idx1 + k - 1];
if (k == 1) return std::min(nums1[idx1], nums2[idx2]);
// normal case new_idx1 = std::min(idx1 + k / 2 - 1, m - 1); new_idx2 = std::min(idx2 + k / 2 - 1, n - 1); pivot1 = nums1[new_idx1]; pivot2 = nums2[new_idx2];