DAY 28
0
AI & Data

## 找LeetCode上簡單的題目來撐過30天啦(DAY28)

Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's, and return the matrix.
You must do it in place.

Example 1:

Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]
Output: [[1,0,1],[0,0,0],[1,0,1]]

Example 2:

Input: matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
Output: [[0,0,0,0],[0,4,5,0],[0,3,1,0]]

Constraints:
• m == matrix.length
• n == matrix[0].length
• 1 <= m, n <= 200
• -231 <= matrix[i][j] <= 231 - 1

• A straightforward solution using O(mn) 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?

``````class Solution {
public void setZeroes(int[][] matrix) {
int i,j=0,k=0,size=(2*matrix[0].length*matrix.length) ;
int[] temp = new int[size];
Arrays.fill(temp, -1);
for(i=0;i<matrix.length;i++){
for(j=0;j<matrix[0].length;j++){
if(matrix[i][j]==0){
temp[k] = i;
temp[k+1]=j;
k=k+2;
}
}
}
for(i=0;i<size;i=i+2){
if(temp[i]<0){
break;
}else{
for(j=0;j<matrix[0].length;j++){
matrix[temp[i]][j] = 0;
}
for(j=0;j<matrix.length;j++){
matrix[j][temp[i+1]] = 0;
}
}
}
}
}

``````

day28心得

### 1 則留言

0
juck30808
iT邦新手 3 級 ‧ 2021-10-14 12:10:06