refactor: improving MedianOfMatrix (#6376)

refactor: improving MedianOfMatrix
This commit is contained in:
Oleksandr Klymenko
2025-07-15 08:23:49 +03:00
committed by GitHub
parent 25aaa6e064
commit 95116dbee4
2 changed files with 26 additions and 10 deletions

View File

@@ -14,19 +14,19 @@ public final class MedianOfMatrix {
}
public static int median(Iterable<List<Integer>> matrix) {
// Flatten the matrix into a 1D list
List<Integer> linear = new ArrayList<>();
List<Integer> flattened = new ArrayList<>();
for (List<Integer> row : matrix) {
linear.addAll(row);
if (row != null) {
flattened.addAll(row);
}
}
// Sort the 1D list
Collections.sort(linear);
if (flattened.isEmpty()) {
throw new IllegalArgumentException("Matrix must contain at least one element.");
}
// Calculate the middle index
int mid = (0 + linear.size() - 1) / 2;
// Return the median
return linear.get(mid);
Collections.sort(flattened);
return flattened.get((flattened.size() - 1) / 2);
}
}