leetcode73—— 矩阵置零

题意:

要求:

 

 我那该死的暴力解法:

class Solution {
    public void setZeroes(int[][] matrix) {
        int m=matrix.length;//行
        int n=matrix[0].length;//列
        //先找出  0所在位置  记录位置  然后 该行 列 都为0
        HashMap<Integer,Integer> hash=new HashMap<>();
        Stack<Integer> srow=new Stack<>();
        Stack<Integer> scol=new Stack<>();
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                if(matrix[i][j]==0){
                    //hash.put(i,j);
                    srow.push(i);
                    scol.push(j);
                }
            }
        }

        while(!srow.empty()){
            int tem=srow.pop();
            for(int i=0;i<n;i++){
                matrix[tem][i]=0;
            }
        }
        while(!scol.empty()){
            int t=scol.pop();
            for(int i=0;i<m;i++){
                matrix[i][t]=0;
            }
        }

        /*Set<Map.Entry<Integer,Integer>> x=hash.entrySet();
        Iterator<Map.Entry<Integer,Integer>> it=x.iterator();
        int row=0;
        int col=0;
        while(it.hasNext()){
            Map.Entry<Integer,Integer> entry=it.next();
            row=entry.getKey();
            col=entry.getValue();

            for(int i=0;i<m;i++){
                matrix[i][col]=0;
            }
            for(int j=0;j<n;j++){
                matrix[row][j]=0;
            }
        }*/

        return;

    }
}

再想想:

好吧还是看了

既然我的暴力解法也知道是标记i  j 

而我用的是用栈分别去保存  

与用布尔类型做标记还是差一点

class Solution {
    public void setZeroes(int[][] matrix) {
        //用两个数组标记
        int m=matrix.length;
        int n=matrix[0].length;

        boolean[] row=new boolean[m];
        boolean[] col=new boolean[n];

        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                if(matrix[i][j]==0){
                    row[i]=true;
                    col[j]=true;
                }
            }
        }

        
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                if(row[i]||col[j]){
                    matrix[i][j]=0;
                }
            }
        }

        return;

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值