Skip to content

Commit 73812d9

Browse files
committed
media in matrix
1 parent 6e693ac commit 73812d9

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed

DSA Crack Sheet/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@
4545

4646
- [Spirally traversing a matrix](https://practice.geeksforgeeks.org/problems/spirally-traversing-a-matrix-1587115621/1# "view question") - [Cpp Solution](./solutions/Spirally%20traversing%20a%20matrix.cpp)
4747
- [Search a 2D Matrix](https://leetcode.com/problems/search-a-2d-matrix/ "view question") - [Cpp Solution](./solutions/Search%20a%202D%20Matrix.cpp)
48+
- [Median in a row-wise sorted Matrix](https://practice.geeksforgeeks.org/problems/median-in-a-row-wise-sorted-matrix1527/1 "view question") - [Cpp Solution](./solutions/Median%20in%20a%20row-wise%20sorted%20Matrix.cpp)
4849
- []( "view question") - [Cpp Solution](./solutions/.cpp)
4950

5051
### Strings
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
/*
2+
Median in a row-wise sorted Matrix
3+
====================================
4+
5+
Given a row wise sorted matrix of size RxC where R and C are always odd, find the median of the matrix.
6+
7+
Example 1:
8+
Input:
9+
R = 3, C = 3
10+
M = [[1, 3, 5],
11+
[2, 6, 9],
12+
[3, 6, 9]]
13+
14+
Output: 5
15+
Explanation:
16+
Sorting matrix elements gives us
17+
{1,2,3,3,5,6,6,9,9}. Hence, 5 is median.
18+
19+
Example 2:
20+
Input:
21+
R = 3, C = 1
22+
M = [[1], [2], [3]]
23+
Output: 2
24+
Your Task:
25+
You don't need to read input or print anything. Your task is to complete the function median() which takes the integers R and C along with the 2D matrix as input parameters and returns the median of the matrix.
26+
27+
Expected Time Complexity: O(32 * R * log(C))
28+
Expected Auxiliary Space: O(1)
29+
30+
Constraints:
31+
1<= R,C <=150
32+
1<= matrix[i][j] <=1000
33+
*/
34+
35+
int median(vector<vector<int>> &m, int r, int c)
36+
{
37+
int min = INT_MAX, max = INT_MIN;
38+
for (int i = 0; i < r; i++)
39+
{
40+
if (m[i][0] < min)
41+
min = m[i][0];
42+
if (m[i][c - 1] > max)
43+
max = m[i][c - 1];
44+
}
45+
46+
int desired = (r * c + 1) / 2;
47+
while (min < max)
48+
{
49+
int mid = min + (max - min) / 2;
50+
int place = 0;
51+
52+
for (int i = 0; i < r; ++i)
53+
{
54+
place += upper_bound(m[i].begin(), m[i].end(), mid) - m[i].begin();
55+
}
56+
if (place < desired)
57+
min = mid + 1;
58+
else
59+
max = mid;
60+
}
61+
return min;
62+
}

0 commit comments

Comments
 (0)