From 1f419ec88116bfa5bde473b6c34f7bf66badb768 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=94=90=E6=A0=91=E6=A3=AE?= Date: Thu, 21 Feb 2019 19:06:48 +0800 Subject: [PATCH] Create 73. Set Matrix Zeroes.md --- solutions/73. Set Matrix Zeroes.md | 33 ++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 solutions/73. Set Matrix Zeroes.md diff --git a/solutions/73. Set Matrix Zeroes.md b/solutions/73. Set Matrix Zeroes.md new file mode 100644 index 0000000..d209f98 --- /dev/null +++ b/solutions/73. Set Matrix Zeroes.md @@ -0,0 +1,33 @@ +# [73. Set Matrix Zeroes](https://leetcode.com/problems/set-matrix-zeroes/) +# 思路 +题目要求将一个矩阵中元素0所在的行和列全部设置为0,要求空间复杂度为O(1)。 +如果不要求空间复杂度的话这题就简单了。先遍历一遍矩阵同时用一个数组(或其他容器)记录所有0的位置,然后再将这些位置对应的行列都设置成0即可。 +但是此方法额外开了一个数组,空间复杂度达不到要求。有没有什么方法能在不开数组的情况下也能记录这些位置呢? +答案是可以的。因为我们只需要记录哪些行、列需要被设置成全0即可(而不需要记录所有0元素的位置)。我们可以用第0行标记哪些列需要设置为全0,用第0列标记哪些行需要设置为全0, +由于第0行和第0列有重叠元素matrix[0][0],所以我们还需要开一个额外的变量来记录第0列(或行)是否需要设置为0。 +时间复杂度O(mn), 空间复杂度O(1) + +# C++ +``` C++ +class Solution { +public: + void setZeroes(vector>& matrix) { + int col0 = 1, r = matrix.size(), c = matrix[0].size(); + for(int i = 0; i < r; i++){ // 记录哪些行、列需要设置为全0 + if(matrix[i][0] == 0) col0 = 0; + for(int j = 1; j < c; j++) + if(matrix[i][j] == 0) + matrix[i][0] = matrix[0][j] = 0; + } + for(int i = 1; i < r; i++){ + for(int j = 1; j < c; j++) + if(matrix[i][0] == 0 || matrix[0][j] == 0) + matrix[i][j] = 0; + } + if(matrix[0][0] == 0) // 处理第0行 + for(int i = 0; i < c; i++) matrix[0][i] = 0; + if(col0 == 0) // 处理第0列 + for(int i = 0; i < r; i++) matrix[i][0] = 0; + } +}; +```