Sunday, February 16, 2014

Find K-th Element in Two Sorted Arrays

Find K-th Element in Two Sorted Arrays
Solution 1:
Very straight thought:
1. merge two sorted array into new Array - C;
2. Get the kth element in C
I think the time complexity is O(n + m), where n is the length of array A, m is the length of Array B.
public class Find_kth_Element_in_Two_Sorted_Array {
 public int mergeGetKthNumber(int[] A, int[] B, int k) {
  int[] C = mergeTwoArrays(A, B);
  return C[k - 1];
 }
 
 public int[] mergeTwoArrays(int[] A, int[] B) {
  int[] C = new int[A.length + B.length];
  int i = 0, j = 0, k = 0;
  while (i < A.length && j < B.length) {
   if (A[i] <= B[j]) {
    C[k] = A[i];
    i++;
   } else {
    C[k] = B[j];
    j++;
   }
   k++;
  }
  while (i < A.length) {
   C[k] = A[i];
   i++;
   k++;
  }
  while (j < B.length) {
   C[k] = B[j];
   j++;
   k++;
  }
  return C;
 }
}
Solution 2
Compare the two arrays elements one by one;
if A[i] <= B[j], i++;
if A[i] > B[j], j++;
if A or B has no element left, then go through (k - i - j) elements in left Array.
I think the time complexity is also O(n + m), same as above.
Solution 3:
Use the binary search, there is something wrong with the code now......

No comments:

Post a Comment