-
Notifications
You must be signed in to change notification settings - Fork 0
/
39) Median in a row-wise sorted Matrix.cpp
84 lines (72 loc) · 1.91 KB
/
39) Median in a row-wise sorted Matrix.cpp
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
//{ Driver Code Starts
//Initial template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
//User function template for C++
class Solution{
public:
int upper_bound(vector<int>&row, int mid){
int l = 0, h = row.size()-1;
while(l<=h){
int m = (l+h)/2;
if(row[m] <= mid){
l = m+1;
}else{
h = m-1;
}
}
return l;
}
int median(vector<vector<int>> &matrix, int r, int c){
// code here
int mini = INT_MAX, maxi = INT_MIN;
//traverse row wise
for(int i=0; i<r; i++){
mini = min(mini, matrix[0][i]);
maxi = max(maxi, matrix[i][c-1]);
}
//define the assumption element
int left = mini, right = maxi;
int pos = (r*c+1)/2;
//check using while loop
while(left <= right){
//calculate mid for binary search suing lowest and highest element
int mid = (left + right)/2;
int place = 0;
int cnt = 0;
//check and count the smaller elements then mid
for(int i=0; i<r; i++){
cnt = upper_bound(matrix[i], mid);
place = place + cnt;
}
if(place < pos){
left = mid + 1;
}else{
right = mid - 1;
}
}
return left;
}
};
//{ Driver Code Starts.
int main()
{
int t;
cin>>t;
while(t--)
{
int r, c;
cin>>r>>c;
vector<vector<int>> matrix(r, vector<int>(c));
for(int i = 0; i < r; ++i)
for(int j = 0;j < c; ++j)
cin>>matrix[i][j];
Solution obj;
int ans=-1;
ans=obj.median(matrix, r, c);
cout<<ans<<"\n";
}
return 0;
}
// } Driver Code Ends