73. Set Matrix Zeroes
来源:互联网 发布:电力系统短路计算软件 编辑:程序博客网 时间:2024/04/28 11:18
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)的情况下,我们需要使用数组本身来记录0的位置。
思考过程:使用m+n个数来分别记录需要清零的行和列,相当于在数组外额外增加一行和一列。
所以我们可以用第一行和第一列来记录matrix[1~m-1][1~n-1]中需要清零的位置。
最后,如果原始数组的第一行和第一列存在0的话,就分别将第一行和第一列清零。
public class Solution { public void setZeroes(int[][] matrix) { int m=matrix.length; int n=matrix[0].length; boolean column=false,row=false; for(int i=0;i<n;i++){ if(matrix[0][i]==0){ row=true; } } for(int i=0;i<m;i++){ if(matrix[i][0]==0){ column=true; } } for(int i=1;i<m;i++){ for(int j=1;j<n;j++){ if(matrix[i][j]==0){ matrix[i][0]=0; matrix[0][j]=0; } } } for(int i=1;i<m;i++){ for(int j=1;j<n;j++){ if(matrix[i][0]==0||matrix[0][j]==0){ matrix[i][j]=0; } } } if(column){ for(int i=0;i<m;i++){ matrix[i][0]=0; } } if(row){ for(int i=0;i<n;i++){ matrix[0][i]=0; } } return; }}
0 0
- 73.Set Matrix Zeroes
- 73. Set Matrix Zeroes
- 73. Set Matrix Zeroes
- 73. Set Matrix Zeroes
- 73. Set Matrix Zeroes
- 73. Set Matrix Zeroes
- 73. Set Matrix Zeroes
- 73. Set Matrix Zeroes
- 73. Set Matrix Zeroes
- 73. Set Matrix Zeroes
- 73. Set Matrix Zeroes
- 73. Set Matrix Zeroes
- 73. Set Matrix Zeroes
- 73. Set Matrix Zeroes
- 73. Set Matrix Zeroes
- 73. Set Matrix Zeroes
- 73. Set Matrix Zeroes
- 73. Set Matrix Zeroes
- Head First设计模式学习笔记-------(2)观察者模式
- 框架之SpringMVC
- 机器学习历史简介
- Codeforces Round #401 (Div. 2):E. Hanoi Factory
- Android 之低版本高版本实现沉浸式状态栏
- 73. Set Matrix Zeroes
- 利用VPS配合Shadowsocks 科学上网
- Java基础(流程控制语句、方法、数组)
- 【HDU-OJ】-6016-Count the Sheep(二分图,vector)
- use vue vuex vue-router, not use webpack
- 51nod 贪心入门之四 独木舟问题
- JAVA 加密技术
- [Azure]使用Powershell输出某台ARM虚拟机的NSG
- Adaboost+Haar