如何在不使用额外空间的情况下解决这个问题?

how to solve this question without using extra space?

本文关键字:解决 情况下 问题 空间      更新时间:2023-10-16

给定一个 m x n 矩阵,如果元素为 0,则将其整行和整列设置为 0。就地执行。

class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
for(int i=0 ; i<matrix.size() ; ++i){
for(int j=0 ; matrix[i].size() ; ++j){
if(matrix[i][j]==0){

int col=0, row=0;
while(col<matrix.size()){
matrix[col][j]=0;
col++;
}
while(row<matrix[i].size()){
matrix[i][row]=0;
row++;
}
break;
}
}
}
}
};

在遍历我得到零的地方时,我使该行和列为零,我不知道为什么我会收到运行时错误

我猜您正在尝试一次性解决它,这是一件好事,但有时它会使解决方案变得复杂。

这个解决方案很容易理解,会通过,并且不需要额外的空间,但我们可以通过多次传递来做到这一点,这完全没问题,因为时间复杂度保持不变。

#include <vector>

class Solution {
public:
void setZeroes(std::vector<std::vector<int>>& matrix) {
bool is_zero_col = false;
bool is_zero_row = false;
int row_length = matrix.size();
int col_length = matrix[0].size();
for (int row = 0; row < row_length; row++) {
if (matrix[row][0] == 0) {
is_zero_col = true;
break;
}
}
for (int col = 0; col < col_length; col++) {
if (matrix[0][col] == 0) {
is_zero_row = true;
break;
}
}
for (int row = 1; row < row_length; row++) {
for (int col = 1; col < col_length; col++)
if (matrix[row][col] == 0) {
matrix[row][0] = 0;
matrix[0][col] = 0;
}
}
for (int row = 1; row < row_length; row++) {
for (int col = 1; col < col_length; col++)
if (matrix[row][0] == 0 || matrix[0][col] == 0) {
matrix[row][col] = 0;
}
}
if (is_zero_col) {
for (int row = 0; row < row_length; row++) {
matrix[row][0] = 0;
}
}
if (is_zero_row) {
for (int col = 0; col < col_length; col++) {
matrix[0][col] = 0;
}
}
}
};
<小时 />

参考资料

  • 有关其他详细信息,您可以查看讨论区。其中有很多公认的解决方案、解释、多种语言的高效算法以及时间/空间复杂性分析。

如果您的矩阵没有等于最大整数值的元素,则的解决方案。 首先找到所有零并为相应的行和列设置最大 int 值。 然后为所有最大值设置零。

class Solution {
public:
void setZeroes(std::vector<std::vector<int>>& matrix) {
constexpr auto max_value = std::numeric_limits<int>::max();
for (auto& col : matrix) {
const auto zeroElem = std::find(col.begin(), col.end(), 0);
if (zeroElem != col.end()) {
std::fill(col.begin(), col.end(), max_value);
const auto index = std::distance(col.begin(), zeroElem);
for (auto& sCol : matrix)
if (index < sCol.size()) {
sCol[index] = max_value;
}
}
}
for (auto& col : matrix)
for (auto& elem : col)
if (max_value == elem)
elem = 0;
}
};
int main(int, char**)
{
std::vector<std::vector<int>> Matrix;
Matrix.insert(Matrix.end(), { 1,1,1,1,1,1 });
Matrix.insert(Matrix.end(), { 1,1,1,1,0,1 });
Matrix.insert(Matrix.end(), { 1,1,1,1,1,1 });
Matrix.insert(Matrix.end(), { 1,1,0,1,1,1 });
Matrix.insert(Matrix.end(), { 1,1,1,1,1,1 });
Solution s;
s.setZeroes(Matrix);
for (auto& sCol : Matrix) {
std::cout << std::endl;
for (auto& Elem : sCol) {
std::cout << Elem << ' ';
}
}
return 0;
}
1 1 0 1 0 1
0 0 0 0 0 0
1 1 0 1 0 1
0 0 0 0 0 0
1 1 0 1 0 1
相关文章: