Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit99971b3

Browse files
author
applewjg
committed
SetMatrixZeroes
Change-Id: Id82c30a5eb860bd4dd0493ba7ae03a1ff247bc07
1 parent6e9cb18 commit99971b3

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

‎SetMatrixZeroes.java

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
/*
2+
Author: King, wangjingui@outlook.com
3+
Date: Dec 25, 2014
4+
Problem: Set Matrix Zeroes
5+
Difficulty: Medium
6+
Source: https://oj.leetcode.com/problems/set-matrix-zeroes/
7+
Notes:
8+
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
9+
Follow up:
10+
Did you use extra space?
11+
A straight forward solution using O(mn) space is probably a bad idea.
12+
A simple improvement uses O(m + n) space, but still not the best solution.
13+
Could you devise a constant space solution?
14+
15+
Solution: Use first row and column as auxiliary spaces instead of newly allocating ones.
16+
*/
17+
publicclassSolution {
18+
publicvoidsetZeroes(int[][]matrix) {
19+
intm =matrix.length;
20+
if(m <=0)return;
21+
intn =matrix[0].length;
22+
23+
booleanrow_has_zero =false;
24+
booleancol_has_zero =false;
25+
26+
for(intj=0;j<n;j++){
27+
if(matrix[0][j]==0){
28+
row_has_zero =true;
29+
break;
30+
}
31+
}
32+
for(inti=0;i<m;i++){
33+
if(matrix[i][0]==0){
34+
col_has_zero =true;
35+
break;
36+
}
37+
}
38+
39+
for(inti=0;i<m;i++){
40+
for(intj=0;j<n;j++){
41+
if(matrix[i][j]==0){
42+
matrix[0][j] =0;
43+
matrix[i][0] =0;
44+
}
45+
}
46+
}
47+
for (inti =1;i <m;i++)
48+
for (intj =1;j <n;j++)
49+
if (matrix[i][0] ==0 ||matrix[0][j] ==0)
50+
matrix[i][j] =0;
51+
52+
if (row_has_zero)
53+
for (inti =0;i <n;i++)
54+
matrix[0][i] =0;
55+
if (col_has_zero)
56+
for (inti =0;i <m;i++)
57+
matrix[i][0]=0;
58+
59+
}
60+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp