背吧
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int n1 = nums1.length, n2 = nums2.length;
int totalLength = n1 + n2;
double ans;
if (totalLength % 2 == 1) {
int midIndex = totalLength / 2;
// 注意midIndex要+1
ans = getKthElement(nums1, nums2, midIndex + 1);
} else {
int midIndex1 = totalLength / 2 - 1, midIndex2 = totalLength / 2;
// 注意midIndex要+1
ans = (getKthElement(nums1, nums2, midIndex1 + 1) + getKthElement(nums1, nums2, midIndex2 + 1)) / 2;
}
return ans;
}
public double getKthElement(int[] nums1, int[] nums2, int k) {
int n1 = nums1.length, n2 = nums2.length;
int index1 = 0, index2 = 0;
while (true) {
if (index1 == n1) return nums2[index2 + k - 1];
if (index2 == n2) return nums1[index1 + k - 1];
if (k == 1) return Math.min(nums1[index1], nums2[index2]);
int half = k / 2;
int newIndex1 = Math.min(index1 + half, n1) - 1;
int newIndex2 = Math.min(index2 + half, n2) - 1;
if (nums1[newIndex1] <= nums2[newIndex2]) {
k -= (newIndex1 - index1 + 1);
index1 = newIndex1 + 1;
} else {
k -= (newIndex2 - index2 + 1);
index2 = newIndex2 + 1;
}
}
}
}