Skip to content

3033. Modify the Matrix 👍

  • Time: $O(mn)$
  • Space: $O(mn)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
 public:
  vector<vector<int>> modifiedMatrix(vector<vector<int>>& matrix) {
    const int m = matrix.size();
    const int n = matrix[0].size();
    vector<vector<int>> ans = matrix;

    for (int j = 0; j < n; ++j) {
      int mx = 0;
      for (int i = 0; i < m; ++i)
        mx = max(mx, matrix[i][j]);
      for (int i = 0; i < m; ++i)
        if (matrix[i][j] == -1)
          ans[i][j] = mx;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public int[][] modifiedMatrix(int[][] matrix) {
    final int m = matrix.length;
    final int n = matrix[0].length;
    int[][] ans = matrix.clone();

    for (int j = 0; j < n; ++j) {
      int mx = 0;
      for (int i = 0; i < m; ++i)
        mx = Math.max(mx, matrix[i][j]);
      for (int i = 0; i < m; ++i)
        if (matrix[i][j] == -1)
          ans[i][j] = mx;
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
  def modifiedMatrix(self, matrix: list[list[int]]) -> list[list[int]]:
    m = len(matrix)
    n = len(matrix[0])
    ans = matrix.copy()

    for j in range(n):
      mx = max(matrix[i][j] for i in range(m))
      for i in range(m):
        if matrix[i][j] == -1:
          ans[i][j] = mx

    return ans