您的位置:首页 > 其它

【leetcode】4. Median of Two Sorted Arrays

2016-10-02 10:58 344 查看
Question

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

nums1 = [1, 3],nums2 = [2],The median is 2.0

nums1 = [1, 2],nums2 = [3, 4],The median is (2 + 3)/2 = 2.5

Solution

1.合并数组(复杂度O(n + m),运行超时)

public class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int length=nums1.length+nums2.length;
int[] num1=new int[length],num2=new int[length];
System.arraycopy(nums1,0,num1,0,nums1.length);
System.arraycopy(nums2,0,num1,nums1.length,nums2.length);
for(int i=0;i<length;i++){
num2[i]=num1[i];
}
int i=0,j=nums1.length,k=i;
for(;i<j&&j<length;k++){
if(num2[i]<num2[j])
num1[k]=num2[i++];
else
num1[k]=num2[j++];
}
for(;i<j;i++){
num1[k++]=num2[i++];
}
for(;j<length;j++){
num1[k++]=num2[j++];
}
if(length%2==1)
return num1[length/2];
else
return (num1[length/2]+num1[length/2+1])/2;
}
}

2.求两个有序数组中的第k个数

public class Solution {
public static double findMedianSortedArrays(int nums1[], int nums2[]) {
int m=nums1.length;
int n=nums2.length;
int length= m+n;
if (length%2!= 0)
return findK(nums1, 0, m-1, nums2, 0, n-1, length/2+1);
else {
double a= findK(nums1, 0, m-1, nums2, 0, n-1, length/2);
double b= findK(nums1, 0, m-1, nums2, 0, n-1, length/2+1);
return (double)(a+b)/2;
}
}
public static int findK(int[] A, int a_start, int a_end, int[] B, int b_start, int b_end, int k) {
int m=a_end-a_start+1;                                        //求数组A的长度
int n=b_end-b_start+1;                                        //求数组B的长度
if(m>n)
return findK(B,b_start,b_end,A,a_start,a_end,k);          //把长度小的数组放前面
if(m==0)
return B[k-1];                                            //A长度为0,那么总数组第k个值即为B中的第k个值
if(k==1)
return Math.min(A[a_start],B[b_start]);                   //求第一个值,即判断数组A,B第一个值的大小
int partA=Math.min(k/2,m);                                    //对每个数组的分半操作
int partB=k-partA;                                            //如果A[k/2-1]<B[k/2-1],那么说明A[0]到A[k/2-1]都不是所求,舍弃
if(A[a_start+partA-1]<B[b_start+partB-1])
return findK(A,a_start+partA,a_end,B,b_start,b_end,k-partA);
else if(A[a_start+partA-1]>B[b_start+partB-1])
return findK(A,a_start,a_end,B,b_start+partB,b_end,k-partB);
else
return A[a_start+partA-1];                                //如果相等,那么即为所求
}
}





内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: