Skip to content

Commit 24e34ef

Browse files
authoredSep 21, 2023
4. Median of Two Sorted Array _(So Hard)_
HARD question
1 parent d0bb0ad commit 24e34ef

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
 

‎4. Median of Two Sorted Array

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
////////////////////////////////////////////////////////////////////////////////////////////////////////
2+
3+
optimized Solution
4+
if(nums2.size() < nums1.size()) return findMedianSortedArrays(nums2, nums1);
5+
int n1 = nums1.size();
6+
int n2 = nums2.size();
7+
int low = 0, high = n1;
8+
while(low <= high){
9+
int cut1 = (low + high) >> 1;
10+
int cut2 = (n1+n2+1)/2 - cut1;
11+
12+
int left1 = cut1 ==0 ? INT_MIN : nums1[cut1-1]; //to much tough
13+
int left2 = cut2 ==0 ? INT_MIN : nums2[cut2 -1];
14+
15+
int right1 = cut1 == n1 ? INT_MAX : nums1[cut1];
16+
int right2 = cut2 == n2 ? INT_MAX : nums2[cut2];
17+
18+
if( left1 <= right2 && left2 <= right1){
19+
if((n1+n2) %2 == 0)
20+
return(max(left1,left2) + min(right1, right2)) / 2.0;
21+
else
22+
return max(left1, left2);
23+
}
24+
else if(left1 > right2){
25+
high = cut1 -1;
26+
}
27+
else{
28+
low = cut1 +1;
29+
}
30+
}
31+
return 0.0;
32+
}

0 commit comments

Comments
 (0)
Please sign in to comment.