题目:There are two sorted arrays nums1 andnums2 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)).
即:给定两个有序数组,在给定的时间复杂度内返回这两个数组的中位数。
1.若为奇数,即为中间的数
2.若为偶数,则为中间两个数的和除以2
个人提交的解法如下:首先算出两个数组的长度和和中位数的index,然后两个数组分别有两个指针,找到指定的位置即可。
思路比较简单,可是要考虑到边界情况,代码如下:
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
double ans = 0;
int totalLength=nums1.length+nums2.length;
boolean odd=false;
if(totalLength%2!=0)
odd=true;
int midIndex=totalLength/2;
int count=0;
int i=0,j=0;
while(i<nums1.length&&j<nums2.length){
int flag;//用于判断当前是哪个数组的指针移动
if(nums1[i]<=nums2[j]){
flag=1;
i++;
}
else {
j++;
flag=2;
}
if((!odd&&(count==midIndex-1)||(count==midIndex))){
if(flag==1)ans+=nums1[i-1];
else ans+=nums2[j-1];
if(count==midIndex)//index已经为中位数,则直接返回
if(odd) return ans;
else return ans/2;
}
count++;
}
if(odd&&ans!=0)//奇数并且前面已经找到了一个数直接返回
return ans;
if(odd&&ans==0){//否则在剩下的数组里面找一个数
if(i==nums1.length)
return nums2[midIndex-i];
else
return nums1[midIndex-j];
}
if(ans==0){//若为偶数的情况且前面一个中位数都没找到
if(i==nums1.length)
return (double)(nums2[midIndex-i-1]+nums2[midIndex-i])/2;
else
return (double)(nums1[midIndex-j-1]+nums1[midIndex-j])/2;
}
else{//为偶数且找到了一个中位数
if(i==nums1.length)
return (double)(nums2[midIndex-i]+ans)/2;
else
return (double)(nums1[midIndex-j]+ans)/2;
}
}