码迷,mamicode.com
首页 > 其他好文 > 详细

Set Matrix Zeroes

时间:2016-07-16 06:26:58      阅读:265      评论:0      收藏:0      [点我收藏+]

标签:

Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.

Example

Given a matrix

[
  [1,2],
  [0,3]
],

return
[
[0,2],
[0,0]
]

Challenge 

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?

Analysis:
 
We are going to use two sets to save all the column numbers and row numbers whose cells need to be set to 0. This will cost O(m + n) space.
 
Another approach is from: http://fisherlei.blogspot.com/2013/01/leetcode-set-matrix-zeroes.html
1.先确定第一行和第一列是否需要清零
2.扫描剩下的矩阵元素,如果遇到了0,就将对应的第一行和第一列上的元素赋值为0
3.根据第一行和第一列的信息,已经可以讲剩下的矩阵元素赋值为结果所需的值了
4.根据1中确定的状态,处理第一行和第一列。


技术分享
 
 
 1 public class Solution {
 2     /**
 3      * @param matrix:
 4      *            A list of lists of integers
 5      * @return: Void
 6      */
 7     public void setZeroes(int[][] matrix) {
 8         if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return;
 9 
10         boolean firstRowZero = false;
11         boolean firstColumnZero = false;
12 
13         // set first row and column zero or not
14         for (int i = 0; i < matrix.length; i++) {
15             if (matrix[i][0] == 0) {
16                 firstColumnZero = true;
17                 break;
18             }
19         }
20 
21         for (int i = 0; i < matrix[0].length; i++) {
22             if (matrix[0][i] == 0) {
23                 firstRowZero = true;
24                 break;
25             }
26         }
27 
28         // mark zeros on first row and column
29         for (int i = 1; i < matrix.length; i++) {
30             for (int j = 1; j < matrix[0].length; j++) {
31                 if (matrix[i][j] == 0) {
32                     matrix[i][0] = 0;
33                     matrix[0][j] = 0;
34                 }
35             }
36         }
37 
38         // use mark to set elements
39         for (int i = 1; i < matrix.length; i++) {
40             for (int j = 1; j < matrix[0].length; j++) {
41                 if (matrix[i][0] == 0 || matrix[0][j] == 0) {
42                     matrix[i][j] = 0;
43                 }
44             }
45         }
46 
47         // set first column and row
48         if (firstColumnZero) {
49             for (int i = 0; i < matrix.length; i++)
50                 matrix[i][0] = 0;
51         }
52 
53         if (firstRowZero) {
54             for (int i = 0; i < matrix[0].length; i++)
55                 matrix[0][i] = 0;
56         }
57     }
58 }

 

 

Set Matrix Zeroes

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5675030.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!