首页 > 代码库 > Leetcode: Set Matrix Zeroes

Leetcode: Set Matrix Zeroes

一次过,空间复杂度为O(m+n), 下一次做的时候寻找constant space solution。用boolean array也可以,用bit vector可能会更节省

 1 import java.util.*;
 2 
 3 public class Solution {
 4     public void setZeroes(int[][] matrix) {
 5         HashSet<Integer> rows = new HashSet<Integer>();
 6         HashSet<Integer> columns = new HashSet<Integer>();
 7         
 8         for (int i = 0; i < matrix.length; i++) {
 9             for (int j = 0; j < matrix[0].length; j++) {
10                 if (matrix[i][j] == 0) {
11                     rows.add(i);
12                     columns.add(j);
13                 }
14             }
15         }
16         
17         for (int i = 0; i < matrix.length; i++){
18             for (int j = 0; j < matrix[0].length; j++) {
19                 if (rows.contains(i) || columns.contains(j)) matrix[i][j] = 0;
20             }
21         }
22     }
23 }