- Notifications
You must be signed in to change notification settings - Fork 19.9k
/
Copy pathMedianOfMatrix.java
32 lines (25 loc) · 844 Bytes
/
MedianOfMatrix.java
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
packagecom.thealgorithms.matrix;
importjava.util.ArrayList;
importjava.util.Collections;
importjava.util.List;
/**
* Median of Matrix (https://medium.com/@vaibhav.yadav8101/median-in-a-row-wise-sorted-matrix-901737f3e116)
* Author: Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi)
*/
publicfinalclassMedianOfMatrix {
privateMedianOfMatrix() {
}
publicstaticintmedian(Iterable<List<Integer>> matrix) {
// Flatten the matrix into a 1D list
List<Integer> linear = newArrayList<>();
for (List<Integer> row : matrix) {
linear.addAll(row);
}
// Sort the 1D list
Collections.sort(linear);
// Calculate the middle index
intmid = (0 + linear.size() - 1) / 2;
// Return the median
returnlinear.get(mid);
}
}