Question:
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
Analysis:
给出一个m * n的矩阵,如果一个元素为0,则它整行整列都设为0.
Answer:
public class Solution { public void setZeroes(int[][] matrix) { ArrayList<Integer> colll = new ArrayList<Integer>(); if(matrix == null) return; int row = matrix.length, col = matrix[0].length; boolean flag = false; for(int i=0; i<row; i++) { flag = false; for(int j=0; j<col; j++) { if(matrix[i][j] == 0) { flag = true; if(!colll.contains(j)) colll.add(j); } } if(flag == true) { for(int j=0; j<col; j++) matrix[i][j] = 0; } } for(int j=0; j<colll.size(); j++) { int temp = colll.get(j); for(int i=0; i<row; i++) matrix[i][temp] = 0; } } }
时间: 2024-10-14 15:09:24