Median Of Two Sorted Arrays
1 var findKth = function(nums1, nums2, k) { 2 if (nums1.length > nums2.length) { 3 return findKth(nums2, nums1, k); 4 } 5 if (nums1.length < 1) { 6 return nums2[k - 1]; 7 } 8 if (k <= 1) { 9 return Math.min(nums1[0], nums2[0]); 10 } 11 12 var p1 = Math.min(Math.floor(k / 2), nums1.length), 13 p2 = k - p1; 14 15 if (nums1[p1 - 1] < nums2[p2 - 1]) { 16 return findKth(nums1.slice(p1), nums2.slice(0, p2), k - p1); 17 } else if (nums1[p1 - 1] > nums2[p2 - 1]) { 18 return findKth(nums1.slice(0, p1), nums2.slice(p2), k - p2) 19 } else { 20 return nums1[p1 - 1]; 21 } 22 }; 23 24 var findMedianSortedArrays = function(nums1, nums2) { 25 var len = nums1.length + nums2.length; 26 if (len & 0x1) { 27 return findKth(nums1, nums2, Math.ceil(len / 2)); 28 } else { 29 return (findKth(nums1, nums2, Math.floor(len / 2)) 30 + findKth(nums1, nums2, Math.floor(len / 2) + 1)) / 2; 31 } 32 }; 33 34 var a = [1, 2], 35 b = [1, 1]; 36 console.log(findMedianSortedArrays(a, b));