4. Median of Two Sorted Arrays
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)).
public class Solution { public double findMedianSortedArrays(int[] nums1, int[] nums2) { int len; if(nums1.length==0){ len = nums2.length; if(len%2==0) return (double)(nums2[len/2-1]+nums2[len/2])/2; else return nums2[len/2]; } if(nums2.length==0){ len = nums1.length; if(len%2==0) return (double)(nums1[len/2-1]+nums1[len/2])/2; else return nums1[len/2]; } len = nums1.length + nums2.length; if(len%2==0) return (double)(findK(nums1,0,nums1.length-1,nums2,0,nums2.length-1, len/2-1)+findK(nums1,0,nums1.length-1,nums2,0,nums2.length-1, len/2))/2; else return findK(nums1,0,nums1.length-1,nums2,0,nums2.length-1, len/2); } public int findK(int[] nums1, int s1, int e1, int[] nums2, int s2, int e2, int k){ //k started from 0 //End condition if(s1==e1){ if(s2+k<=e2 //avoid overflow && nums1[s1]>nums2[s2+k]) return nums2[s2+k]; else if(k==0 //avoid overflow || nums1[s1]>nums2[s2+k-1]) return nums1[s1]; else return nums2[s2+k-1]; } if(s2==e2){ if(s1+k<=e1 && nums2[s2]>nums1[s1+k]) return nums1[s1+k]; else if(k==0 || nums2[s2]>nums1[s1+k-1]) return nums2[s2]; else { return nums1[s1+k-1]; } } int m1 = (s1+e1) >> 1; //middle(for odd) or left middle(for even) int m2 = (s2+e2) >> 1; if(k > (e1+e2-s1-s2)/2){ //K is at the second half if(nums1[m1] < nums2[m2]){ //delete first half of nums1 return findK(nums1, m1+1, e1, nums2, s2, e2, k-(m1-s1+1)); } else{ //delete first half of nums2 return findK(nums1, s1, e1, nums2, m2+1, e2, k-(m2-s2+1)); } } else{//K is at the first half if(nums1[m1] < nums2[m2]){ //delete second half of nums2 return findK(nums1, s1, e1, nums2, s2, m2, k); } else{ //delete second half of nums1 return findK(nums1, s1, m1, nums2, s2, e2, k); } } } }