题目如下:
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)).
解题思路:
思路1:最直接的一种思路就是将两个有序的数组合并nums3,然后从nums3里找出中位数。当然处理的时候会有一些细节,具体的处理请看代码。
思路1提交的代码:
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
double num = 0;
int m = nums1.length;
int n = nums2.length;
if(nums2.length == 0){
if(m % 2 == 0){
num = (nums1[m /2 - 1] + nums1[m / 2 ]) / 2.0;
System.out.println(num);
}else{
num = nums1[m / 2];
}
return num;
}
if(nums1.length == 0){
if(n % 2 == 0){
num = (nums2[n /2 - 1] + nums2[n / 2 ]) / 2.0;
System.out.println(num);
}else{
num = nums2[n / 2];
}
return num;
}
int index1 = 0;
int index2 = 0;
int[] nums3 = new int[n + m];
int k = 0;
while(index1 < m && index2 < n ){
if(nums1[index1] < nums2[index2]){
nums3[k++] = nums1[index1++];
}else{
nums3[k++] = nums2[index2++];
}
}
while(index1 < m){
nums3[k++] = nums1[index1++];
}
while(index2 < n){
nums3[k++] = nums2[index2++];
}
if((m + n) % 2 == 0){
num = (nums3[(m + n)/2 - 1] + nums3[(m + n) / 2 ]) / 2.0;
}else{
num = nums3[(m + n) / 2];
}
return num;
}
思路2:思路1存在的问题:我们在求中位数的时候根本不关系具体的数,关心的是数值在列表中的位置,试想我们仅仅对两个数组的前半部分(或者后半部分)进行合并,找到中位数的位置之后就停止,岂不是要节约时间。
思路2提交的代码:
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
double num = 0;
int m = nums1.length;
int n = nums2.length;
if(nums2.length == 0){
if(m % 2 == 0){
num = (nums1[m /2 - 1] + nums1[m / 2 ]) / 2.0;
System.out.println(num);
}else{
num = nums1[m / 2];
}
return num;
}
if(nums1.length == 0){
if(n % 2 == 0){
num = (nums2[n /2 - 1] + nums2[n / 2 ]) / 2.0;
System.out.println(num);
}else{
num = nums2[n / 2];
}
return num;
}
if(m + n == 2){
num = (nums1[m - 1] + nums2[n - 1]) / 2.0;
return num;
}
int index1 = 0;
int index2 = 0;
int cell = (int) Math.floor((m + n)/2.0) + 1;
int[] nums3 = new int[cell];
int k = 0;
while(index1 < m && index2 < n){
if(nums1[index1] < nums2[index2]){
nums3[k++] = nums1[index1++];
}else{
nums3[k++] = nums2[index2++];
}
if ( (index1 + index2) >= cell ) {
break;
}
}
while(index1 < m && (index1 + index2) < cell){
nums3[k++] = nums1[index1++];
}
while(index2 < n && (index1 + index2) < cell){
nums3[k++] = nums2[index2++];
}
if((m + n) % 2 == 0){
num = (nums3[cell - 2 ] + nums3[cell - 1 ]) / 2.0;
}else{
num = nums3[cell - 1];
}
return num;
}
从理论上讲,第二种方法对于大数据集来说会更加节约时间,但是从leetcode提交结果后的效果,第二种的时间不太理想。