1
+ /*
2
+ @lc id : 4
3
+ @problem : Median of Two Sorted Arrays
4
+ @author : rohit
5
+ @url : https://leetcode.com/problems/median-of-two-sorted-arrays/
6
+ @difficulty : hard
7
+ */
8
+
9
+ class Solution {
10
+
11
+ public double findMedianSortedArrays (int [] input1 , int [] input2 ) {
12
+
13
+ //if input1 length is greater than input2 length, switch
14
+ //so that num1 length is smaller
15
+
16
+ if (input1 .length > input2 .length )
17
+ return findMedianSortedArrays (input2 , input1 );
18
+
19
+ int x = input1 .length ;
20
+ int y = input2 .length ;
21
+
22
+ //We will do binary search on input1
23
+
24
+ int low = 0 ;
25
+ int high = x ;
26
+
27
+ while (low <= high ){
28
+ int partitionX = (low + high ) / 2 ;
29
+
30
+ /* partitionX + partitionY should be equal to (x+y+1) / 2
31
+ (x+y) is sum of length of both arrays, we need to find mid
32
+ therefore we are looking for (x+y) / 2 but for it to work for both even
33
+ and odd length, we use (x+y+1) / 2 */
34
+
35
+ int partitionY = (x +y +1 )/2 - partitionX ;
36
+
37
+ //if partitionX is 0, there is nothing on left side and we have to
38
+ //compare max of left side X with right side Y min, so we take max as -inf
39
+ int maxLeftX = (partitionX == 0 ) ? Integer .MIN_VALUE : input1 [partitionX - 1 ];
40
+
41
+ /*If partitionX = x, there is nothing on right side of X, and we have to compare
42
+ max of leftY with min of rightX for partition to be valid, So we take minRightX = +INF */
43
+ int minRightX = (partitionX == x ) ? Integer .MAX_VALUE : input1 [partitionX ];
44
+
45
+ int maxLeftY = (partitionY == 0 ) ? Integer .MIN_VALUE : input2 [partitionY - 1 ];
46
+ int minRightY = (partitionY == y ) ? Integer .MAX_VALUE : input2 [partitionY ];
47
+
48
+
49
+ if (maxLeftX <= minRightY && maxLeftY <= minRightX ){
50
+ /*We have partitioned array at correct place
51
+ Now if combined lenght is even, get max of left and min of right
52
+ If it is odd, get max of left*/
53
+
54
+ if ((x +y ) % 2 == 0 )
55
+ return (double ) (Math .max (maxLeftX , maxLeftY ) + Math .min (minRightX , minRightY ) ) / 2 ;
56
+
57
+ else return (double ) Math .max (maxLeftX , maxLeftY );
58
+
59
+
60
+ }
61
+
62
+ //We are too far on right side, go on left side
63
+ else if (maxLeftX > minRightY )
64
+ high = partitionX - 1 ;
65
+
66
+ //We are too far on left size, go to right side
67
+ else low = partitionX + 1 ;
68
+
69
+ }
70
+
71
+ return 0.0 ;
72
+
73
+ }
74
+
75
+ }
0 commit comments