王廷瑋|數位醫療|智慧醫療: 73. Set Matrix Zeroes WFU

2024年7月4日 星期四

73. Set Matrix Zeroes

73. Set Matrix Zeroes

給定一個 m x n 的整數矩陣 matrix,如果一個元素是 0,則將其所在的整行和整列設置為 0。

你必須就地完成此操作。
範例 1:

輸入:matrix = [[1,1,1],[1,0,1],[1,1,1]] 輸出:[[1,0,1],[0,0,0],[1,0,1]]


Python


class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
m, n = len(matrix), len(matrix[0])
rows, cols = set(), set()

# First pass: record the rows and columns that need to be zeroed
for i in range(m):
for j in range(n):
if matrix[i][j] == 0:
rows.add(i)
cols.add(j)

# Second pass: set the rows and columns to zero
for i in range(m):
for j in range(n):
if i in rows or j in cols:
matrix[i][j] = 0

17.41MB, 102ms


C++


#include <vector>
#include <unordered_set>

using namespace std;

class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
int m = matrix.size();
int n = matrix[0].size();
unordered_set<int> rows, cols;

// First pass: record the rows and columns that need to be zeroed
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (matrix[i][j] == 0) {
rows.insert(i);
cols.insert(j);
}
}
}

// Second pass: set the rows and columns to zero
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (rows.find(i) != rows.end() || cols.find(j) != cols.end()) {
matrix[i][j] = 0;
}
}
}
}
};

17.41MB, 14ms


Javascript


/**
* @param {number[][]} matrix
* @return {void} Do not return anything, modify matrix in-place instead.
*/
var setZeroes = function(matrix) {
const m = matrix.length;
const n = matrix[0].length;
let rows = new Set();
let cols = new Set();

// First pass: record the rows and columns that need to be zeroed
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (matrix[i][j] === 0) {
rows.add(i);
cols.add(j);
}
}
}

// Second pass: set the rows and columns to zero
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (rows.has(i) || cols.has(j)) {
matrix[i][j] = 0;
}
}
}
};

53.08MB, 66ms