-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path62-Matrix Median
61 lines (53 loc) · 1.15 KB
/
62-Matrix Median
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <algorithm>
int countSmallerThanMid(vector<int> &row, int mid)
{
int l = 0, h = row.size() - 1;
while (l <= h)
{
int md = (l + h) >> 1;
if (row[md] <= mid)
{
l = md + 1;
}
else
{
h = md - 1;
}
}
return l;
}
int getMedian(vector<vector<int>> &matrix)
{
// Write your code here.\
//Approxh 1 - strore all matrix elements in ans array and sort them
//then return the median according to size
int n=matrix.size();
int m=matrix[0].size();
// vector<int> ans;
// for(int i=0;i<n;i++){
// for(int j=0;j<m;j++){
// ans.push_back(matrix[i][j]);
// }
// }
// sort(ans.begin(),ans.end());
// int len=ans.size();
// if(len%2!=0){
// return ans[len/2];
// }
// else{
// return ans[len/2 +1];
// }
//Approach-2 using Binary Search
int low=1;
int high=1e9;
while(low<=high){
int mid=(low+high) >> 1;
int cnt=0;
for(int i=0;i<n;i++){
cnt+=countSmallerThanMid(matrix[i],mid);
}
if(cnt <= (n*m)/2) low=mid+1;
else high=mid-1;
}
return low;
}