LintCode: 矩阵归零

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;
                }
            }
        }
    }
}

你可能感兴趣的:(python)