LintCode: 矩阵归零

来源:互联网 发布:中核原子能公司 知乎 编辑:程序博客网 时间:2024/04/30 23:43

LintCode: 矩阵归零

Python

class Solution:    """    @param matrix: A list of lists of integers    @return: Nothing    """    def setZeroes(self, matrix):        # write your code here        row = []        col = []        for i in range(len(matrix)):            for j in range(len(matrix[0])):                if matrix[i][j] == 0:                    row.append(i)                    col.append(j)        row = list(set(row))        col = list(set(col))        for i in range(len(matrix)):            for j in range(len(matrix[0])):                if i in row or j in col:                    matrix[i][j] = 0

Java

public class Solution {    /**     * @param matrix: A list of lists of integers     * @return: Void     */    public void setZeroes(int[][] matrix) {        // write your code here        if(matrix.length == 0){            return ;        }        HashSet<Integer> row = new HashSet();        HashSet<Integer> col = new HashSet();        for(int i=0; i<matrix.length; i++){            for(int j=0; j<matrix[0].length; j++){                if(matrix[i][j] == 0){                    row.add(i);                    col.add(j);                }            }        }        for(int i=0; i<matrix.length; i++){            for(int j=0; j<matrix[0].length; j++){                if(row.contains(i) || col.contains(j)){                    matrix[i][j] = 0;                }            }        }    }}
0 0
原创粉丝点击