**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
**
但要求是O(log(m+n))
我开始没注意就用了归并排序,竟然过了
amazing。
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
if( nums1.length == 0 && nums2.length == 0){
double result = 0.0;
return result;
}
int []nums3 = new int[nums1.length + nums2.length];
int i = 0 ;
int j = 0;
int k = 0;
while (i < nums1.length && j < nums2.length){
if (nums1[i] < nums2[j]){
nums3[k++] = nums1[i++];
}else {
nums3[k++] = nums2[j++];
}
}
while (i < nums1.length){
nums3[k++] = nums1[i++];
}
while (j < nums2.length){
nums3[k++] = nums2[j++];
}
if (nums3.length % 2 == 0){
double result = ((double)nums3[nums3.length/2] + (double)nums3[nums3.length/2-1])/2;
return result;
}
else{
double result = nums3[nums3.length/2];
return result;
}
}
}
但是作为努力学习的码畜,当然不能止步于此
所以又去研究别人的算法
Ozx
竟然用递归解决。
高高高,的确是O(log(m+n))
首先判断奇数偶数,递归寻找中位数,最精妙的就是findkth的最后那个k参数,当然两个到零的函数判断返回也是有点难想到,比我的算法好多,佩服佩服
public class Solution {
public double findMedianSortedArrays(int A[], int B[]) {
int len = A.length + B.length;
if (len % 2 == 1) {
return findKth(A, 0, B, 0, len / 2 + 1);
}
return (
findKth(A, 0, B, 0, len / 2) + findKth(A, 0, B, 0, len / 2 + 1)
) / 2.0;
}
// find kth number of two sorted array
public static int findKth(int[] A, int A_start,
int[] B, int B_start,
int k){
if (A_start >= A.length) {
return B[B_start + k - 1];
}
if (B_start >= B.length) {
return A[A_start + k - 1];
}
if (k == 1) {
return Math.min(A[A_start], B[B_start]);
}
int A_key = A_start + k / 2 - 1 < A.length
? A[A_start + k / 2 - 1]
: Integer.MAX_VALUE;
int B_key = B_start + k / 2 - 1 < B.length
? B[B_start + k / 2 - 1]
: Integer.MAX_VALUE;
if (A_key < B_key) {
return findKth(A, A_start + k / 2, B, B_start, k - k / 2);
} else {
return findKth(A, A_start, B, B_start + k / 2, k - k / 2);
}
}
}