当前位置:   article > 正文

leetcode 矩阵置零 java_lecode如果一个元素为0,将其所在横和列都设为0

lecode如果一个元素为0,将其所在横和列都设为0

题干

给定一个 m x n 的矩阵,如果一个元素为 0,则将其所在行和列的所有元素都设为 0。请使用原地算法。

示例 1:

输入:
[
[1,1,1],
[1,0,1],
[1,1,1]
]
输出:
[
[1,0,1],
[0,0,0],
[1,0,1]
]
示例 2:

输入:
[
[0,1,2,0],
[3,4,5,2],
[1,3,1,5]
]
输出:
[
[0,0,0,0],
[0,4,5,0],
[0,3,1,0]
]
进阶:

一个直接的解决方案是使用 O(mn) 的额外空间,但这并不是一个好的解决方案。
一个简单的改进方案是使用 O(m + n) 的额外空间,但这仍然不是最好的解决方案。
你能想出一个常数空间的解决方案吗?

想法

题干交代的很清楚,每一个0的那一列和那一行都要全部置为0;
那么我们遍历每一个数,找到是0的那个数就将那一列那一行置为0就可以了。
但是在代码层面真的可以吗?
如果在给你的这个matrix上这么操作会有一个巨大的问题:
会继续循环下去,因为有新的0出现,最终这个矩阵全部变为0;

所以我们有了这样的想法:
先遍历一遍,记录为0位置的坐标
在遍历一遍更改这些位置的行列为0;

代码

class Solution {
    public void setZeroes(int[][] matrix) {
        //长
        int chang=matrix.length;
        //宽
        int kuan=matrix[0].length;
        List<List<Integer>> list=new ArrayList<>();//用来存坐标
        for(int i=0;i<chang;i++){
            for(int j=0;j<kuan;j++){
                if(matrix[i][j]==0){
                    List<Integer> tem=new ArrayList<>();//暂存给定的坐标
                    tem.add(i);//横坐标
                    tem.add(j);//纵坐标
                    list.add(tem);
                }
            }
        }
        
        for(int k=0;k<list.size();k++){
            for(int i=0;i<chang;i++){
                matrix[i][list.get(k).get(1)]=0;//一列为0
            }
           for(int i = 0; i < kuan; i++) {
                matrix[list.get(k).get(0)][i] = 0;//一行为0
            }
 
            
            }              

        }
        
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

大佬的代码,用两个数组来存坐标,非常奥力给,效率高的一批

class Solution {
    public void setZeroes(int[][] matrix) {
       int row = matrix.length;
       if(row == 0){
           return;
       }
       int col = matrix[0].length;
       int rows[] = new int[row];
       int cols[] = new int [col];
       for(int i = 0;i<row;i++){
           for(int j=0;j<col;j++){
               if(matrix[i][j]==0){
                   rows[i]=1;
                   cols[j]=1;
                    setZero(i,j,matrix);
               }else if(rows[i]==1 || cols[j]==1){
                   matrix[i][j]=0;
               }
           }
       } 
    }

    public void setZero(int i, int j, int[][]matrix){
        for(int row=0;row<i;row++){
            matrix[row][j]=0;
        }
        for(int col=0;col<j;col++){
            matrix[i][col]=0;
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/257160
推荐阅读
相关标签
  

闽ICP备14008679号