[LeetCode] 73. Set Matrix Zeroes Java

题目:

iven 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?

题意及分析:如果一个矩阵的元素为0,那么其所在行和所在列都设置为0,能不能使用空间复杂度为o(1)

代码一:遍历matrix,分别用两个集合记录需要变化的行和列,然后在遍历设置,空间复杂度为0(m+ns)

 1 class Solution {
 2     public void setZeroes(int[][] matrix) {
 3         int row = matrix.length;
 4         if(row==0) return;
 5         int col = matrix[0].length;
 6 
 7         Set<Integer> rowSet = new HashSet<>();
 8         Set<Integer> colSet = new HashSet<>();
 9 
10         for(int i=0;i<row;i++){
11             for(int j=0;j<col;j++){
12                 if(matrix[i][j]==0){
13                     rowSet.add(i);
14                     colSet.add(j);
15                 }
16             }
17         }
18 
19         //
20         Iterator<Integer> iterator = rowSet.iterator();
21         while(iterator.hasNext()){
22             Integer res = iterator.next();
23             for(int i=0;i<col;i++){
24                 matrix[res][i] = 0;
25             }
26         }
27 
28         iterator = colSet.iterator();
29         while(iterator.hasNext()){
30             Integer res = iterator.next();
31             for(int i=0;i<row;i++){
32                 matrix[i][res] = 0;
33             }
34         }
35     }
36 }

代码二:不使用额外空间的方法类似,就是把第一行和第一列作为标记。 首先 先判断第一行第一列是否含有0,并用两个bool变量记录起来。这样,遍历一遍之后就把所有的行和列都在第一行和第一列中体现出来。接下来就是,根据第一行和第一列的0元素,把其所在的行和列置0,不包括第一行和第一列。

 1 class Solution {
 2     public void setZeroes(int[][] matrix) {
 3         int row = matrix.length;
 4         if(row==0) return;;
 5         int col = matrix[0].length;
 6         boolean fr = false,fc = false;
 7         for(int i=0;i<row;i++){
 8             for(int j=0;j<col;j++){
 9                 if(matrix[i][j]==0){
10                     if(i == 0) fr = true;
11                     if(j == 0) fc = true;
12                     matrix[0][j]=0;
13                     matrix[i][0]=0;
14                 }
15             }
16         }
17         //根据第一行和第一列的0元素,把其所在的行和列置0,不包括第一行和第一列。
18         for(int i=1;i<row;i++) {
19             for (int j = 1; j < col; j++) {
20                 if(matrix[i][0] == 0 || matrix[0][j] == 0) {
21                     matrix[i][j] = 0;
22                 }
23             }
24         }
25 
26 
27         //最后如果第一行有或者第一列原来就有为0的元素,置为0
28         if(fr){
29             for(int i=0;i<col;i++){
30                 matrix[0][i] = 0;
31             }
32         }
33         if(fc) {
34             for(int i = 0; i < row; i++) {
35                 matrix[i][0] = 0;
36             }
37         }
38     }
39 }

 

posted @ 2017-12-21 14:37  荒野第一快递员  阅读(179)  评论(0编辑  收藏  举报