[InterviewBit] Median of Array

Median of Array

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
double Solution::findMedianSortedArrays(const vector<int> &A, const vector<int> &B) {
int n = A.size(), m = B.size();
if(n > m) return findMedianSortedArrays(B,A);
int l = 0, r = n, med = (n + m) / 2;
while(l <= r) {
int i = l + (r - l) / 2;
int j = med - i;
if(i > 0 and A[i-1] > B[j]) r = i - 1;
else if(i < n and A[i] < B[j-1]) l = i + 1;
else {
int r = (i == n) ? B[j] : (j == m) ? A[i] : min(A[i],B[j]);
if((n + m) & 1) return r;
int l = (i == 0) ? B[j-1] : (j==0) ? A[j-1] : max(A[i-1],B[j-1]);
return (l + r) / 2.;
}
}
return -1;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/09/30/PS/interviewbit/median-of-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.