天天看點

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[])):
                if matrix[i][j] == :
                    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[])):
                if i in row or j in col:
                    matrix[i][j] = 
           

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 == ){
            return ;
        }
        HashSet<Integer> row = new HashSet();
        HashSet<Integer> col = new HashSet();
        for(int i=; i<matrix.length; i++){
            for(int j=; j<matrix[].length; j++){
                if(matrix[i][j] == ){
                    row.add(i);
                    col.add(j);
                }
            }
        }
        for(int i=; i<matrix.length; i++){
            for(int j=; j<matrix[].length; j++){
                if(row.contains(i) || col.contains(j)){
                    matrix[i][j] = ;
                }
            }
        }
    }
}