标签:
标题: | Set Matrix Zeroes |
通过率: | 31.3% |
难度: | 中等 |
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
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 int m=matrix.length; 4 int n=matrix[0].length; 5 boolean falg=false,mb=false,nb=false; 6 7 for(int i=0;i<m;i++){ 8 if(matrix[i][0]==0){ 9 mb=true; 10 } 11 } 12 for(int i=0;i<n;i++){ 13 if(matrix[0][i]==0){ 14 nb=true; 15 } 16 } 17 for(int i=0;i<m;i++){ 18 for(int j=0;j<n;j++){ 19 if(matrix[i][j]==0){ 20 matrix[i][0]=0; 21 matrix[0][j]=0; 22 } 23 } 24 } 25 for(int i=1;i<m;i++){ 26 for(int j=1;j<n;j++){ 27 if(matrix[i][0]==0||matrix[0][j]==0){ 28 matrix[i][j]=0; 29 } 30 } 31 } 32 if(mb){ 33 for(int i=0;i<m;i++){ 34 matrix[i][0]=0; 35 } 36 } 37 if(nb){ 38 for(int i=0;i<n;i++){ 39 matrix[0][i]=0; 40 } 41 } 42 } 43 44 45 46 }
leetcode------Set Matrix Zeroes
标签:
原文地址:http://www.cnblogs.com/pkuYang/p/4281072.html