Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
Follow up:
Did you use extra space?
A straight forward solution using O(m**n) space is probably a bad idea.
A simple improvement uses O(m + n) space, but still not the best solution.
Could you devise a constant space solution?
思路
想法比较简单,把0所在的坐标记录下来,再把所有对应的行和列置为零即可。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| public class Solution { public void setZeroes(int[][] matrix) { List<Integer> lines = new ArrayList<Integer>(); List<Integer> cols = new ArrayList<Integer>(); for(int i = 0; i < matrix.length; i++){ for(int j = 0; j < matrix[i].length; j++){ if(matrix[i][j] == 0){ lines.add(i); cols.add(j); } } } for(int i = 0; i < lines.size(); i++){ int cur = lines.get(i); for(int j = 0; j < matrix[cur].length; j++){ matrix[cur][j] = 0; } } for(int i = 0; i < cols.size(); i++){ int cur = cols.get(i); for(int j = 0; j < matrix.length; j++){ matrix[j][cur] = 0; } } } }
|