-
Notifications
You must be signed in to change notification settings - Fork 343
/
MedianinRowWiseSortedMatrix.cpp
63 lines (49 loc) · 1.4 KB
/
MedianinRowWiseSortedMatrix.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
// Problem link : https://practice.geeksforgeeks.org/problems/median-in-a-row-wise-sorted-matrix1527/1
#include <bits/stdc++.h>
using namespace std;
class Solution{
public:
int median(vector<vector<int>> &matrix, int r, int c){
// code here
int minElement = INT_MAX;
int maxELement = INT_MIN;
for(int i=0; i<r; i++) {
minElement = min(minElement, matrix[i][0]);
maxELement = max(maxELement, matrix[i][c-1]);
}
int desiredElements = (r*c+1)/2;
while(minElement < maxELement) {
int currentElements = 0;
int mid = minElement + (maxELement- minElement)/2;
for(int i=0; i<r; i++) {
currentElements += upper_bound(matrix[i].begin(), matrix[i].end(), mid) - matrix[i].begin();
}
if(currentElements< desiredElements) {
minElement = mid+1;
} else {
maxELement = mid;
}
}
return minElement;
}
};
// Input:
// R = 3, C = 3
// M = [[1, 3, 5],
// [2, 6, 9],
// [3, 6, 9]]
// Output: 5
// Explanation:
// Sorting matrix elements gives us
// {1,2,3,3,5,6,6,9,9}. Hence, 5 is median.
int main()
{
int r=3, c=3;
vector<vector<int>> matrix(r, vector<int>(c));
matrix[0] = {1,3,5};
matrix[1] = {2,6,9};
matrix[2] = {3,6,9};
Solution obj;
cout<<obj.median(matrix, r, c)<<endl;
return 0;
}