forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMedianOfMatrix.java
More file actions
32 lines (25 loc) · 879 Bytes
/
MedianOfMatrix.java
File metadata and controls
32 lines (25 loc) · 879 Bytes
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
package com.thealgorithms.matrix;
import java.util.ArrayList;
import java.util.Collections;
import java.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)
*/
public final class MedianOfMatrix {
private MedianOfMatrix() {
}
public static int median(Iterable<List<Integer>> matrix) {
List<Integer> flattened = new ArrayList<>();
for (List<Integer> row : matrix) {
if (row != null) {
flattened.addAll(row);
}
}
if (flattened.isEmpty()) {
throw new IllegalArgumentException("Matrix must contain at least one element.");
}
Collections.sort(flattened);
return flattened.get((flattened.size() - 1) / 2);
}
}