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

矩阵置零

时间:2019-09-01 18:22:01      阅读:71      评论:0      收藏:0      [点我收藏+]

标签:leetcode   hashset   pre   tco   column   public   problem   tps   col   

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/set-matrix-zeroes
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

要求把0所在的行和列的其他元素全部置零,可以先遍历矩阵,找到所有元素为0的位置并记录,再根据遍历的结果把其他的元素置零即可。

public void setZeroes(int[][] matrix) {
        int R = matrix.length;
        int C = matrix[0].length;
        Set<Integer> row = new HashSet<Integer>();
        Set<Integer> col = new HashSet<Integer>();
        
        for(int i = 0; i < R; i++)
        {
            for(int j = 0; j < C; j++)
            {
                if(matrix[i][j] == 0)
                {
                    row.add(i);
                    col.add(j);
                }
            }
        }
        
        for(int i = 0; i < R; i++)
        {
            for(int j = 0; j < C; j++)
            {
                if(row.contains(i) || col.contains(j))
                {
                    matrix[i][j] = 0;
                }
            }
        }
    }

 

矩阵置零

标签:leetcode   hashset   pre   tco   column   public   problem   tps   col   

原文地址:https://www.cnblogs.com/WakingShaw/p/11443024.html

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