首页 > 代码库 > Set Matrix Zeroes
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?
1 public class Solution { 2 public void setZeroes(int[][] matrix) { 3 if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return; 4 int row = 0, col = 0; 5 boolean sig = true; 6 for(int i = 0; i < matrix.length; i ++){ 7 for(int j = 0; j < matrix[0].length; j ++){ 8 if(matrix[i][j] == 0){ 9 if(sig){10 row = i;11 col = j;12 sig = false;13 } else {14 matrix[row][j] = 0;15 matrix[i][col] = 0;16 }17 }18 }19 }20 if(sig) return;21 for(int i = 0; i < matrix.length; i ++){22 for(int j = 0; j < matrix[0].length; j ++){23 if((matrix[row][j] == 0 || matrix[i][col] == 0) && i != row && j != col) matrix[i][j] = 0;24 }25 }26 for(int i = 0; i < matrix.length; i ++){27 matrix[i][col] = 0;28 }29 for(int j = 0; j < matrix[0].length; j ++){30 matrix[row][j] = 0;31 }32 }33 }
Set Matrix Zeroes
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。