|
| 1 | +class Solution { |
| 2 | + public double findMedianSortedArrays(int[] nums1, int[] nums2) { |
| 3 | + |
| 4 | + //Easy for Binary search on smaller length array |
| 5 | + //Checking the length and calling the main Function with smaller len array as forst array |
| 6 | + if(nums1.length > nums2.length){ |
| 7 | + return findMedianSortedArrays(nums2,nums1); |
| 8 | + } |
| 9 | + |
| 10 | + int len1 = nums1.length; |
| 11 | + int len2 = nums2.length; |
| 12 | + //System.out.println(len1 + " " + len2); |
| 13 | + |
| 14 | + //Doing Binary search on smaller array |
| 15 | + int start = 0; |
| 16 | + int end = len1; |
| 17 | + while(start<=end){ |
| 18 | + int partion1 = (start+end)/2; |
| 19 | + int partion2 = ((len1+len2+1)/2 - partion1); |
| 20 | + |
| 21 | + //finding the max and min lenemt is num1 array |
| 22 | + int max1 = (partion1 == 0 ) ? Integer.MIN_VALUE : nums1[partion1-1]; |
| 23 | + int min1 = (partion1 == len1) ? Integer.MAX_VALUE : nums1[partion1]; |
| 24 | + |
| 25 | + //finding the max and min elemnt of nums2 array |
| 26 | + int max2 = (partion2 == 0 ) ? Integer.MIN_VALUE : nums2[partion2-1]; |
| 27 | + //System.out.println(Integer.MIN_VALUE + " " + Integer.MAX_VALUE); |
| 28 | + int min2 = (partion2 == len2) ? Integer.MAX_VALUE : nums2[partion2]; |
| 29 | + |
| 30 | + if(max1 <= min2 && max2 <= min1){ |
| 31 | + if((len1 + len2 ) %2 == 0){ |
| 32 | + return (double)(Math.max(max1, max2) + Math.min(min1, min2))/2; |
| 33 | + }else{ |
| 34 | + return (double)Math.max(max1,max2); |
| 35 | + } |
| 36 | + }else if( max1 > min2){ |
| 37 | + end = partion1 - 1; |
| 38 | + }else{ |
| 39 | + start = partion1 + 1; |
| 40 | + } |
| 41 | + } |
| 42 | + return 0; |
| 43 | + } |
| 44 | +} |
0 commit comments