var findMedianSortedArrays = function(nums1, nums2) {
if(nums1.length > nums2.lenth) {
var tmp = nums2;
nums2 = nums1;
nums1 = tmp;
}
var len1 = nums1.length,
len2 = nums2.length,
len = len1 + len2;
if(len % 2 == 0) {
halfLen = len / 2;
console.log(halfLen);
return (findKth(nums1, 0, nums2, 0, halfLen) + findKth(nums1, 0, nums2, 0, halfLen + 1)) / 2;
} else {
halfLen = (len + 1) / 2;
return findKth(nums1, 0, nums2, 0, halfLen);
}
};
var findKth = function(arr1, start1, arr2, start2, k) {
var halfK = Math.floor(k / 2);
if(start1 >= arr1.length) return arr2[start2 + k - 1]; //如果数组arr1已经全部获取完,直接在数组arr2获取第k个元素
if(start2 >= arr2.length ) return arr1[start1 + k - 1];
if(k == 1) return Math.min(arr1[start1], arr2[start2]); //如果获取的是第一个元素,且两个数组都有值
var index1 = start1 + halfK - 1,
index2 = start2 + halfK - 1,
v1 = index1 < arr1.length ? arr1[index1] : Infinity,
v2 = index2 < arr2.length ? arr2[index2] :Infinity;
if(v1 >= v2) {
start2 = index2 + 1;
} else {
start1 = index1 + 1;
}
k = k - halfK;
return findKth(arr1, start1, arr2, start2, k);
}