73. Set Matrix Zeroes
Last updated
Last updated
如果行列中有元素為0, 讓整行或整列為0
提問:
function header, parameter
test input
說明想法
先標記0的位置, 掃描若為被標記的位置則將其row, col設為0
測試計算複雜度
O (m + n)解:
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
vector<bool> rowFlag(matrix.size(), false);
vector<bool> colFlag(matrix[0].size(), false);
for (int i = 0; i < matrix.size(); i++) {
for (int j = 0; j < matrix[i].size(); j++) {
if (matrix[i][j] == 0) {
rowFlag[i] = true;
colFlag[j] = true;
continue;
}
}
}
for (int i = 0; i < matrix.size(); i++) {
for (int j = 0; j < matrix[i].size(); j++) {
if (rowFlag[i] || colFlag[j]) {
matrix[i][j] = 0;
}
}
}
}
};
O(1)解: 用第一行, 列記錄
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
int m = matrix.size(), n = matrix[0].size();
bool isFirstRowZero = false, isFirstColZero = false;
for (int i = 0; i < m; i++){
if (matrix[i][0] == 0) {
isFirstColZero = true;
}
}
for (int i = 0; i < n; i++){
if (matrix[0][i] == 0) {
isFirstRowZero = true;
}
}
for (int i = 1; i < m; i++){
for (int j = 1; j < n; j++) {
if (matrix[i][j] == 0) {
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
}
for (int i = 1; i < m; i++){
if (matrix[i][0] == 0) {
for (int j = 0; j < n; j++){
matrix[i][j] = 0;
}
}
}
for (int j = 1; j < n; j++){
if (matrix[0][j] == 0) {
for (int i = 0; i < m; i++){
matrix[i][j] = 0;
}
}
}
if (isFirstColZero) {
for (int i = 0; i < m; i++){
matrix[i][0] = 0;
}
}
if (isFirstRowZero) {
for (int i = 0; i < n; i++){
matrix[0][i] = 0;
}
}
}
};