标签:
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
空间复杂度很容易做到O(m+n), 题目建议最好做到O(1)
/*空间复杂度为O(m+n)*/
void setZeros(vector<vector<int>> &matrix) { int rows = matrix.size(); int colums = matrix[0].size(); int *row_flags = new int[rows]; int *colum_flags = new int[colums]; memset(row_flags, 1, rows*sizeof(int)); memset(colum_flags, 1, colums*sizeof(int)); for (size_t i = 0; i < rows; i++) { for (size_t j = 0; j < colums; j++) { if (matrix[i][j]==0) { row_flags[i] = colum_flags[j] = 0; } } } for (size_t i = 0; i < rows; i++) { if (row_flags[i]==0) { for (size_t j = 0; j < colums; j++) { matrix[i][j] = 0; } } } for (size_t i = 0; i < colums; i++) { if (colum_flags[i]==0) { for (size_t j = 0; j < rows; j++) { matrix[j][i] = 0; } } } }
/* *空间复杂度为O(1) *复用第一行和第一列,先标记第一行和第一列是否有0元素,然后遍历矩阵,如果有0就将该元素的行列第一个元素标记为0. */ void setZeros_v2(vector<vector<int>> &matrix) { int rows = matrix.size(); int colums = matrix[0].size(); int first_rows_have_zero = 0,first_colum_have_zero=0; //标记第一行是否有0元素 for (size_t i = 0; i < colums; i++) { if (matrix[0][i]==0) { first_rows_have_zero = 1; break; } } //标记第一列是否有0元素 for (size_t i = 0; i < rows; i++) { if (matrix[i][0]==0) { first_colum_have_zero = 1; break; } } //复用第一行和第一列,如果有0元素就将该元素的行列第一个元素置0 for (size_t i = 1; i < rows; i++) { for (size_t j = 1; j < colums; j++) { if (matrix[i][j]==0) { matrix[0][j] = 0; matrix[i][0] = 0; } } } //遍历,如果第一行第一列的元素为0,则该元素应为0 for (size_t i = 1; i < rows; i++) { for (size_t j = 1; j < colums; j++) { if (matrix[0][j]==0||matrix[i][0]==0) { matrix[i][j] = 0; } } } //讨论第一列是否含0 if (first_colum_have_zero) { for (size_t i = 0; i < rows; i++) { matrix[i][0] = 0; } } //讨论第一行是否含0 if (first_rows_have_zero) { for (size_t i = 0; i < colums; i++) { matrix[0][i] = 0; } } }
标签:
原文地址:http://www.cnblogs.com/panweishadow/p/4786997.html