标签:leetcode array matrix 算法 algorithm
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
Follow up:
Did you use extra space?
A straight forward solution using O(mn) space is probably a bad idea.
A simple improvement uses O(m + n) space, but still not the best solution.
Could you devise a constant space solution?
我的解题思路如下:遍历矩阵,分别用每一行的首元素保存该行的信息(若为0则表示需要将改行全部设为0),每一列的首元素保存该列的信息,之后根据这些信息进行设置。由于首行首列公用元素matrix[0][0],所以另外设置两个标志row0和col0,分别表示是否需要将首行、首列置0。
我的C++代码实现如下:
void setZeroes(vector<vector<int> > &matrix) { int row0 = 1; for (int j = 0; j < matrix[0].size(); ++j) if (matrix[0][j] == 0) { row0 = 0; break; } int col0 = 1; for (int i = 0; i < matrix.size(); ++i) if (matrix[i][0] == 0) { col0 = 0; break; } for (int i = 1; i < matrix.size(); ++i) for (int j = 1; j < matrix[i].size(); ++j) if (matrix[i][j] == 0) { matrix[i][0] = 0; matrix[0][j] = 0; } for (int i = 1; i < matrix.size(); ++i) if (matrix[i][0] == 0) for (int j = 1; j < matrix[i].size(); ++j) matrix[i][j] = 0; for (int j = 1; j < matrix[0].size(); ++j) if (matrix[0][j] == 0) for (int i = 1; i < matrix.size(); ++i) matrix[i][j] = 0; if (row0 == 0) for (int j = 0; j < matrix[0].size(); ++j) matrix[0][j] = 0; if (col0 == 0) for (int i = 0; i < matrix.size(); ++i) matrix[i][0] = 0; }
matrix[0][0]其实可以用来保存首列元素的信息,所以只需要额外增加首行元素的标志就行:
void setZeroes(vector<vector<int> > &matrix) { int row0 = 1; for (int j = 0; j < matrix[0].size(); ++j) if (matrix[0][j] == 0) { row0 = 0; break; } for (int i = 1; i < matrix.size(); ++i) for (int j = 0; j < matrix[i].size(); ++j) if (matrix[i][j] == 0) { matrix[i][0] = 0; matrix[0][j] = 0; } for (int i = 1; i < matrix.size(); ++i) if (matrix[i][0] == 0) for (int j = 1; j < matrix[i].size(); ++j) matrix[i][j] = 0; for (int j = 0; j < matrix[0].size(); ++j) if (matrix[0][j] == 0) for (int i = 1; i < matrix.size(); ++i) matrix[i][j] = 0; if (row0 == 0) for (int j = 0; j < matrix[0].size(); ++j) matrix[0][j] = 0; }
LeetCode[Array]: Set Matrix Zeroes
标签:leetcode array matrix 算法 algorithm
原文地址:http://blog.csdn.net/chfe007/article/details/41623245