Set Matrix Zeroes
来源:互联网 发布:sqlmap mssql 编辑:程序博客网 时间:2024/06/05 14:49
public class Solution { public void setZeroes(int[][] matrix) { // O(1) space solution // The first row and the first column boolean firstRowHasZero = false, firstColHasZero = false; for(int j = 0; j < matrix[0].length; j++) { if(matrix[0][j] == 0) { firstRowHasZero = true; break; } } for(int i = 0; i < matrix.length; i++) { if(matrix[i][0] == 0) { firstColHasZero = true; break; } } // Rest part for(int i = 1; i < matrix.length; i++) { for(int j = 1; j < matrix[0].length; j++) { if(matrix[i][j] == 0) { matrix[0][j] = 0; // Updates the first row matrix[i][0] = 0; // Updates the first column; } } } // Clears the matrix according to the first row and the first column // and the two booleans for(int i = 1; i < matrix.length; i++) { for(int j = 1; j < matrix[0].length; j++) { if(matrix[0][j] == 0 || matrix[i][0] == 0) { matrix[i][j] = 0; } } } if(firstRowHasZero) { for(int j = 0; j < matrix[0].length; j++) { matrix[0][j] = 0; } } if(firstColHasZero) { for(int i = 0; i < matrix.length; i++) { matrix[i][0] = 0; } } }}
Time: O(m * n)
Space: O(1)
0 0
- LeetCode: Set Matrix Zeroes
- Set Matrix Zeroes
- Set Matrix Zeroes
- LeetCode Set Matrix Zeroes
- [Leetcode] Set Matrix Zeroes
- LeetCode: Set Matrix Zeroes
- Set Matrix Zeroes
- Leetcode: Set Matrix Zeroes
- [LeetCode] Set Matrix Zeroes
- Set Matrix Zeroes
- Set Matrix Zeroes
- [LeetCode]Set Matrix Zeroes
- Set Matrix Zeroes
- Set Matrix Zeroes
- Set Matrix Zeroes
- [leetcode]Set Matrix Zeroes
- Leetcode:Set Matrix Zeroes
- Set Matrix Zeroes
- Linux学习笔记6:shell简介与TCP/IP协议
- [002]kafka消息流通结构
- MFC List Control 报表使用方法
- FDRGV
- web短信注册漏洞探索(成佩涛黑客)
- Set Matrix Zeroes
- HDU1004:Let the Balloon Rise
- OCP 1Z0 053 89
- Linux 火狐浏览器安装Flash插件
- 数据库事务的隔离级别
- C++ string转double
- 90/10原理
- 手把手教你-gdb调试
- tomcat简介之web.xml详解