Find median of two sorted arrays (merge approach)
Java
Hard
4 views
Problem Description
Task: return median of two sorted arrays using merge-like walk (O(n+m)).
Output Format
Return value
Constraints
Handle even length as average (double).
Official Solution
static double median2(int[] a,int[] b){int n=a.length,m=b.length;int total=n+m;int i=0,j=0;int prev=0,cur=0;for(int k=0;k<=total/2;k++){prev=cur;if(i<n && (j>=m || a[i]<=b[j])) cur=a[i++]; else cur=b[j++];}if((total&1)==1) return cur;return (prev+cur)/2.0;}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!