首页 > 代码库 > 55. Set Matrix Zeroes
55. Set Matrix Zeroes
Set Matrix Zeroes
(Link: https://oj.leetcode.com/problems/set-matrix-zeroes/)
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
click to show follow up.
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 元素,分别将其投影在记下的行和列上(做标记)。遍历之后,对于所有行中的标记,将其所在列都置为 0; 对于所有列中标记,将其所在行都置为 0. (最后置标记的行和列为 0. 可含在上述步骤) 时间: O(n2), 空间 : O(1)
class Solution {public: void setZeroes(vector<vector<int> > &matrix) { if(!matrix.size() || !matrix[0].size()) return; const int INF = 1001; int row = matrix.size(), col = matrix[0].size(); int u = -1, v = -1; for(int r = 0; r < row; ++r) for(int c = 0; c < col; ++c) { if(matrix[r][c] == 0) { if(u == -1) { u = r, v = c; continue; } matrix[u][c] = INF; matrix[r][v] = INF; } } if(u == -1) return; if(matrix[u][v] == INF) matrix[u][v] = 0; for(int c = 0; c < col; ++c) { if(matrix[u][c] == INF) { for(int i = 0; i < row; ++i) matrix[i][c] = 0; } else matrix[u][c] = 0; } for(int r = 0; r < row; ++r) { if(matrix[r][v] == INF) { for(int j = 0; j < col; ++j) matrix[r][j] = 0; } else matrix[r][v] = 0; } }};
55. Set Matrix Zeroes
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。