MCPcopy Create free account
hub / github.com/Tiwarishashwat/InterviewCodes / findMedianSortedArrays

Method findMedianSortedArrays

MedianOfSortedArrays.java:3–39  ·  view source on GitHub ↗
(int[] nums1, int[] nums2)

Source from the content-addressed store, hash-verified

1
2class Solution {
3public double findMedianSortedArrays(int[] nums1, int[] nums2) {
4
5// When length are different then apply binary search on shortest array to avoid index out of bound
6 if(nums1.length > nums2.length){
7 return(findMedianSortedArrays(nums2, nums1));
8 }
9 int n1=nums1.length;
10 int n2=nums2.length;
11 int lo=0,hi=n1;
12 while(lo<=hi)
13 {
14// Initialize the cuts or partitions
15 int cut1=lo+(hi-lo)/2;
16// Total required - already present
17 int cut2=((n1+n2)/2)-cut1;
18
19// Initialize l1,l2,r1,r2
20 int l1= (cut1==0)?Integer.MIN_VALUE:nums1[cut1-1];
21 int l2= (cut2==0)?Integer.MIN_VALUE:nums2[cut2-1];
22 int r1= (cut1==n1)?Integer.MAX_VALUE:nums1[cut1];
23 int r2= (cut2==n2)?Integer.MAX_VALUE:nums2[cut2];
24
25// Shift element to the left
26 if(l1>r2) hi=cut1-1;
27 else if(l2>r1) lo=cut1+1;
28 else
29 {
30// Check for even length
31 if((n1+n2)%2==0)
32 return (double)(Math.max(l1,l2)+Math.min(r1,r2))/2;
33 else
34 return (double)(Math.min(r1,r2));
35 }
36// To avoid error
37 }
38 return 0.0;
39 }
40}
41
42

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected