topic
Given two ordered arrays of size and nums1 m and n nums2.
Please find both the median and orderly array, and requires time complexity of the algorithm is O (log (m + n)).
You can not assume nums1 both empty and nums2
Examples
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
General idea
Topic is very simple to understand, to find the median, how complexity is o (m + n), I believe there are some programming experience will do, so the difficulties in the o (log (m + n)). In fact, this problem is to compute the number of k only. When the total number is even, we are seeking a number and a number behind it. We implemented recursively. Recursive function used to find the number of k, each recursive update the value of k (note that an array is empty can be directly returned), each recursion / 2 us to compare the position of two arrays k, the smaller 0 to k / 2 of that part of the array can be discarded, which has been recursively until 1 returns an array, the specific situation classification codes is more intuitive to see or k is empty.
Code
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int mid_left = 0;
int mid_right = 0;
//奇偶的情况
mid_left=findk(nums1,nums2,(nums1.length+nums2.length+1)/2);
if((nums1.length+nums2.length)%2==1){
return mid_left;
}
mid_right=findk(nums1, nums2,(nums1.length+nums2.length+2)/2);
return ((double)mid_left+(double)mid_right)/2;
}
//k表示当前寻找第k大的数
public int findk(int[] nums1,int[] nums2,int k){
//nums1为空,直接从nums2中取
if(nums1.length==0) return nums2[k-1];
//nums2为空,直接从nums1中取
if(nums2.length==0) return nums1[k-1];
//第一个元素
if(k==1) return Math.min(nums1[0], nums2[0]);
//drop表示可能丢去的部分
int drop1=Math.min(k/2, nums1.length);
int drop2=Math.min(k/2, nums2.length);
if(nums1[drop1-1]<=nums2[drop2-1]){//丢去nums1的部分
return findk(Arrays.copyOfRange(nums1, drop1, nums1.length), nums2, k-drop1);
}else{
return findk(nums1,Arrays.copyOfRange(nums2,drop2, nums2.length),k-drop2);//丢去nums2的部分
}
}
public static void main(String[] args) {
int a[]={1,3};
int b[]={2,4};
problem4 c=new problem4();
System.out.println(c.findMedianSortedArrays(a, b));
}