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)).
思路:类似于归并排序,找到一半的排好序的序列,最后一个(或最后两个数的平均数)即为所求,注意边界条件检查即可。
import java.util.ArrayList;
public class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
ArrayList<Integer> list = new ArrayList<>();
int length1 = nums1.length;
int length2 = nums2.length;
int count = length1 + length2;
if (length1 == 0 && length2 == 0) {
return 0;
}
if (length1 == 0) {
if (length2 % 2 == 0) {
return (nums2[length2 / 2 - 1] + nums2[length2 / 2]) / 2.0;
} else {
if (length2 == 1) {
return nums2[0];
} else {
return nums2[length2 / 2];
}
}
}
if (length2 == 0) {
if (length1 % 2 == 0) {
return (nums1[length1 / 2 - 1] + nums1[length1 / 2]) / 2.0;
} else {
if (length1 == 1) {
return nums1[0];
} else {
return nums1[length1 / 2];
}
}
}
int medianIndex = count / 2;
int index1 = 0;
int index2 = 0;
for (int i = 0; i <= medianIndex; i++) {
if (index1 < length1 && index2 < length2) {
if (nums1[index1] < nums2[index2]) {
list.add(nums1[index1]);
index1++;
} else {
list.add(nums2[index2]);
index2++;
}
} else if (index1 < length1) {
list.add(nums1[index1]);
index1++;
} else if (index2 < length2) {
list.add(nums2[index2]);
index2++;
}
}
if (count % 2 == 0) {
int num1 = list.get(list.size() - 2);
int num2 = list.get(list.size() - 1);
return (num1 + num2) / 2.0;
} else {
return list.get(list.size() - 1);
}
}
}