Advertisement
sweet1cris

Untitled

Jan 9th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.14 KB | None | 0 0
  1. public class Solution {
  2.     public double findMedianSortedArrays(int A[], int B[]) {
  3.         int len = A.length + B.length;
  4.         if (len % 2 == 1) {
  5.             return findKth(A, 0, B, 0, len / 2 + 1);
  6.         }
  7.         return (
  8.             findKth(A, 0, B, 0, len / 2) + findKth(A, 0, B, 0, len / 2 + 1)
  9.         ) / 2.0;
  10.     }
  11.  
  12.     // find kth number of two sorted array
  13.     public static int findKth(int[] A, int A_start,
  14.                               int[] B, int B_start,
  15.                               int k){      
  16.         if (A_start >= A.length) {
  17.             return B[B_start + k - 1];
  18.         }
  19.         if (B_start >= B.length) {
  20.             return A[A_start + k - 1];
  21.         }
  22.  
  23.         if (k == 1) {
  24.             return Math.min(A[A_start], B[B_start]);
  25.         }
  26.        
  27.         int A_key = A_start + k / 2 - 1 < A.length
  28.                     ? A[A_start + k / 2 - 1]
  29.                     : Integer.MAX_VALUE;
  30.         int B_key = B_start + k / 2 - 1 < B.length
  31.                     ? B[B_start + k / 2 - 1]
  32.                     : Integer.MAX_VALUE;
  33.        
  34.         if (A_key < B_key) {
  35.             return findKth(A, A_start + k / 2, B, B_start, k - k / 2);
  36.         } else {
  37.             return findKth(A, A_start, B, B_start + k / 2, k - k / 2);
  38.         }
  39.     }
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement