4. Median of Two Sorted Arrays
4. Median of Two Sorted Arrays
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
Example 1:
nums1 = [1, 3] nums2 = [2] The median is 2.0
Example 2:
nums1 = [1, 2] nums2 = [3, 4] The median is (2 + 3)/2 = 2.5
1 /** 2 * @param {number[]} nums1 3 * @param {number[]} nums2 4 * @return {number} 5 */ 6 7 8 var findMedianSortedArrays = function(nums1, nums2) { 9 10 //题目要求时间复杂度在log(n)的范围,而且是给定有序数组, 11 //可以转化为找第K大的数,思想就是二分查找。 12 function findkth(a,m,b,n,k){ 13 14 //保证a的查找范围 小于 b的 15 if(m > n){ 16 return findkth(b,n,a,m,k); 17 } 18 19 //因为m<n 所以n>0 20 if(m == 0){ 21 return b[k-1]; 22 } 23 24 25 if(k == 1){ 26 return Math.min(a[0],b[0]); 27 } 28 29 var pa = Math.min(k>>1,m),pb = k - pa; 30 31 if(a[pa - 1] < b[pb -1]){ 32 return findkth(a.slice(pa),m-pa,b,n,k-pa); 33 }else if(a[pa -1] > b[pb -1]){ 34 //console.log(a,m,b.slice(pb),n-pb,k-pb); 35 return findkth(a,m,b.slice(pb),n-pb,k-pb); 36 }else{ 37 return a[pa-1]; 38 } 39 40 } 41 42 var n = nums1.length; 43 var m = nums2.length; 44 var total = n + m; 45 var k = total>>1; 46 47 //奇数的话 48 if(total & 0x1){ 49 return findkth(nums1,n,nums2,m,k+1); 50 }else{ 51 return (findkth(nums1,n,nums2,m,k) + findkth(nums1,n,nums2,m,k+1))/2; 52 } 53 };