LeetCode 73. Set Matrix Zeros(矩阵赋零)
Posted 几米空间
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 73. Set Matrix Zeros(矩阵赋零)相关的知识,希望对你有一定的参考价值。
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.
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?
题目标签:Array
Java Solution:
Runtime beats 23.97%
完成日期:07/23/2017
关键词:Array
关键点:把原题给的十字改0的这一个过程分解成四个步骤来实现
1 public class Solution 2 { 3 public void setZeroes(int[][] matrix) 4 { 5 boolean firstRow = false; 6 boolean firstCol = false; 7 8 // iterate the first row and column to see any zeros there 9 for(int y=0; y<matrix[0].length; y++) 10 { 11 if(matrix[0][y] == 0) 12 { 13 firstRow = true; 14 break; 15 } 16 } 17 18 for(int x=0; x<matrix.length; x++) 19 { 20 if(matrix[x][0] == 0) 21 { 22 firstCol = true; 23 break; 24 } 25 } 26 27 // iterate rest rows and columns, 28 //if see any zero, put zero in corresponding position in first row and first column 29 for(int x=1; x<matrix.length; x++) // rows 30 { 31 for(int y=1; y<matrix[0].length; y++) // columns 32 { 33 if(matrix[x][y] == 0) 34 { 35 matrix[x][0] = 0; 36 matrix[0][y] = 0; 37 } 38 } 39 } 40 41 // iterate rest rows and columns again, 42 // for each position, if corresponding first row or first column has 0, change this to 0 43 for(int x=1; x<matrix.length; x++) 44 { 45 for(int y=1; y<matrix[0].length; y++) 46 { 47 if(matrix[x][0] == 0 || matrix[0][y] == 0) 48 matrix[x][y] = 0; 49 } 50 } 51 52 53 // check two boolean firstRow and firstCol, and decide need to make first row and first column to 0 54 if(firstRow) 55 for(int y=0; y<matrix[0].length; y++) 56 matrix[0][y] = 0; 57 58 if(firstCol) 59 for(int x=0; x<matrix.length; x++) 60 matrix[x][0] = 0; 61 } 62 }
参考资料:
http://www.cnblogs.com/grandyang/p/4341590.html
LeetCode 算法题目列表 - LeetCode Algorithms Questions List
以上是关于LeetCode 73. Set Matrix Zeros(矩阵赋零)的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 73. Set Matrix Zeroes
[leetcode]73.Set Matrix Zeroes
Leetcode 73: Set Matrix Zeroes
[leetcode][73] Set Matrix Zeroes