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
Code
/**
* @author liyiheng
*/
public class Solution {
public double findMedianSortedArrays(
int[] nums1,
int[] nums2) {
int len1 = nums1.length;
int len2 = nums2.length;
int count = (len1 + len2) /
2 +
1;
int temp1 =
0, temp2 =
0;
int index1 =
0, index2 =
0;
for (
int i =
0; i < count; i++) {
temp1 = temp2;
if (index1==len1){
temp2 = nums2[index2];
index2++;
}
else if (index2==len2){
temp2 = nums1[index1];
index1++;
}
else {
if (nums1[index1] < nums2[index2]) {
temp2 = nums1[index1];
index1++;
}
else {
temp2 = nums2[index2];
index2++;
}
}
}
if ((len1+len2)%
2!=
0){
return temp2;
}
return ((
double) (temp1 + temp2))/
2;
}
}
转载请注明原文地址: https://ju.6miu.com/read-3284.html