Question:
Given sorted Arrays A, B of size M and N respectively. Find the k-th smallest element in the union of A and B. You can assume that there is no duplicate elements.
Http://leetcode.com/2011/01/find-k-th-smallest-element-in-union-of.html
A Special Case:median of the sorted arrays
https://oj.leetcode.com/problems/median-of-two-sorted-arrays/
Http://leetcode.com/2011/03/median-of-two-sorted-arrays.html
option a: two pointers//public int kmin (Int[] a, int[] b, int k) { int a = 0; // [0, a.length - 1] int b = 0; // [0, B.length - 1] int r = -1; for (int i = 0 ; i < k ; i ++) { int va = safevalue (A, a); int vb = safevalue (b, b); if (VA&NBSP;<&NBSP;VB) { r = va; a&Nbsp;++; } else { r = vb; b ++ ; } } return r;} Private int safevalue (int[] a, int i) { if (i < 0 | | i >= a.length) return integer.min_value ; return a[i];}
A Binary Search Solution:
given a[i] and b[j]// if b[j-1] < a[i] < b[j]//// A[i] must be the (i + j + 1) th min number//public int kmin (int[] a, int alow, int ahigh, int[] B, int blow, int Bhigh, int k) { // assumptions... int i = selecti (a, alow, ahigh, b, blow, bhigh, k); int j = (k - 1) - 1; int Ai_1 = i <= 0 ? Integer.MIN_VALUE : A[i - 1]; int&nbsP ai = i >= a.length ? integer.max_value : a[i]; int bj_1 = j <= 0 ? integer.min_value : b[j - 1]; int bj = j >= b.length ? Integer.MAX_VALUE : B[j]; if (bj_1 &NBSP;<&NBSP;AI&NBSP;&&&NBSP;AI&NBSP;<&NBSP;BJ) return ai; if (ai_1 < bj && bj < ai) return Bj // Now, it must be // Ai < Bj_1 < Bj // or // bj <&nbSp ai_1 < ai if (AI&NBSP;<&NBSP;BJ) // Target must be in [Ai+1, Ahigh] X [Blow, Bj-1] { return kmin (A, i + 1, ahigh, b, blow, j - 1, k); } else { return kmin (A, alow, i - 1, b, j + 1, bhigh, k); }}// a methods determine i for A[i]// j in B[j] would be (k - 1) - i// the max value of i is k - 1.private int selecti (int[] a, int alow, int ahigh, int[] B, int blow, int bhigh, int k) { // just choosing the middle number in a. int i = alow + (Ahigh - alow) / 2; i = math.min (i, k - 1); return i;}
[Leetcode] Find the k-th smallest Element in the Union of the Sorted Arrays