题目

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?

分析

题目给定一个m∗n矩阵,要求将矩阵中值为0的元素所在的整行、整列元素均赋值为0;

重点是要求算法是本地,也就是说空间复杂度为O(1)

具体思路如下:

利用矩阵的第一行和第一列来作为辅助空间使用,不用开辟新的存储空间。

方法就是:

1.先确定第一行和第一列是否需要清零

即,看看第一行中是否有0,记下来;也同时记下来第一列中有没有0。

2.扫描剩下的矩阵元素,如果遇到了0,就将对应的第一行和第一列上的元素赋值为0

这里不用担心会将本来第一行或第一列的1改成了0,因为这些值最后注定要成为0的,比如matrix[i][j]==0,那么matrix[i][0]处在第i行,matrix[0][j]处于第j列,最后都要设置为0的。

3.根据第一行和第一列的信息,已经可以将剩下的矩阵元素赋值为结果所需的值了即,拿第一行为例,如果扫描到一个0,就将这一列都清0.

4.根据1中确定的状态,处理第一行和第一列。

如果最开始得到的第一行中有0的话,就整行清零。同理对列进行处理。

AC代码

class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) { if (matrix.empty())
return; //求得所给矩阵的行数、列数
int m = matrix.size();
int n = matrix.front().size(); //初始化首行,首列标志位false,代表元素不为0
bool f_row = false, f_col = false; for (int j = 0; j < n; j++)
{
if (matrix[0][j] == 0)
{
f_row = true;
break;
}//if
}//for //记录首行、首列的状态
for (int i = 0; i < m; i++)
{
if (matrix[i][0] == 0)
{
f_col = true;
break;
}//if
}//for //下面用原矩阵的首行和首列作为本地存储空间,因为首行首列单独处理,所以下标均从1开始
for (int i = 1; i < m; i++)
{
for (int j = 1; j < n; j++)
{
//如果元素(i,j)为0,则将该元素对应的首行位置(0,j)以及首列位置(i,0)值赋为0
if (matrix[i][j] == 0)
{
matrix[0][j] = 0;
matrix[i][0] = 0;
}//if
}//for
}//for //下面根据首行,首列元素值,更新矩阵中的0
for (int j = 1; j < n; j++)
{
//找到元素为0的坐标,将矩阵中该列元素全部更改为0
if (matrix[0][j] == 0)
{
for (int i = 0; i < m; i++)
matrix[i][j] = 0;
}//if
} for (int i = 1; i < m; i++)
{
if (matrix[i][0] == 0)
{
for (int j = 0; j < n; j++)
matrix[i][j] = 0;
}//if
}//for //最后处理首行和首列
if (f_row)
{
for (int j = 0; j < n; j++)
matrix[0][j] = 0;
} if (f_col)
{
for (int i = 0; i < m; i++)
matrix[i][0] = 0;
} }
};

GitHub测试程序源码

LeetCode(73)Set Matrix Zeroes的更多相关文章

  1. LeetCode(73):矩阵置零

    Medium! 题目描述: 给定一个 m x n 的矩阵,如果一个元素为 0,则将其所在行和列的所有元素都设为 0.请使用原地算法. 示例 1: 输入: [   [1,1,1],   [1,0,1], ...

  2. LeetCode(172)Factorial Trailing Zeroes

    题目 Given an integer n, return the number of trailing zeroes in n!. Note: Your solution should be in ...

  3. LeetCode(59)SPiral Matrix II

    题目 Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. F ...

  4. LeetCode(54)Spiral Matrix

    题目 Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral ...

  5. Qt 学习之路 2(73):Qt 线程相关类

    Home / Qt 学习之路 2 / Qt 学习之路 2(73):Qt 线程相关类 Qt 学习之路 2(73):Qt 线程相关类  豆子  2013年11月26日  Qt 学习之路 2  7条评论 希 ...

  6. LeetCode(275)H-Index II

    题目 Follow up for H-Index: What if the citations array is sorted in ascending order? Could you optimi ...

  7. LeetCode(220) Contains Duplicate III

    题目 Given an array of integers, find out whether there are two distinct indices i and j in the array ...

  8. LeetCode(154) Find Minimum in Rotated Sorted Array II

    题目 Follow up for "Find Minimum in Rotated Sorted Array": What if duplicates are allowed? W ...

  9. LeetCode(122) Best Time to Buy and Sell Stock II

    题目 Say you have an array for which the ith element is the price of a given stock on day i. Design an ...

随机推荐

  1. hdu1162 Eddy's picture 基础最小生成树

    #include <cstdio> #include <cmath> #include <cstring> #include <algorithm> # ...

  2. LINUX 文件夹打包

    tar -zcvf /data/www.tar.gz data/www tar -zcvf 打包后生成的文件名全路径 要打包的目录 压缩: 压缩当前的文件夹 zip -r ./xahot.zip ./ ...

  3. mybatis javaConfig实现

    @Bean public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception { SqlSessio ...

  4. re正则表达式公式讲解6

    标识符 re.I (re.IGNORECASE) 忽略大小写 import re s = "Max@123uyt146" print(re.search("m" ...

  5. JSP报错The value for the useBean class attribute *** is invalid.

    环境:IDEA+Tomcat9+JDK1.8 在前期学习时,环境一直能够"正常"使用,实际上环境并没有完全搭建成功. 推荐: https://blog.csdn.net/lw_po ...

  6. synchronize早已经没那么笨重

    我发现一些同学在网络上有看不少synchronize的文章,可能有些同学没深入了解,只看了部分内容,就急急忙忙认为不能使用它,很笨重,因为是采用操作系统同步互斥信号量来实现的.关于这类的对于synch ...

  7. 问题处理:Cannot find module (SNMPv2-TC): At line 10 in /usr/share/snmp/mibs/UCD-DLMOD-MIB.txt

    在执行  php -i |grep redis 时显示以下报错信息(但在phpinfo查看时一切正常): MIB search path: /root/.snmp/mibs:/usr/share/sn ...

  8. [转载]ant和maven的区别

    Ant是软件构建工具,Maven的定位是软件项目管理和理解工具.Maven除了具备Ant的功能外,还增加了以下主要的功能: 1)使用Project Object Model来对软件项目管理: 2)内置 ...

  9. python_使用qrcode生成二维码

    1.功能 使用qrcode生成二维码 2.代码 #生成二维码: import qrcode #根据url生成二维码 def qrcodeWithUrl(url): img = qrcode.make( ...

  10. Error:Failed to resolve: com.afollestad:material-dialogs:

    http://www.chenruixuan.com/archives/1068.html 背景: 同事把Android项目直接考给了我...我在Android Studio上运行,然后提示: Err ...