码迷,mamicode.com
首页 > 其他好文 > 详细

Set Matrix Zeroes

时间:2014-09-05 07:39:10      阅读:261      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   ar   strong   for   div   

Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.

click to show follow up.

Follow up:

Did you use extra space?
A straight forward 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?

 
 1 public class Solution {
 2     public void setZeroes(int[][] matrix) {
 3         if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return;
 4         int row = 0, col = 0;
 5         boolean sig = true;
 6         for(int i = 0; i < matrix.length; i ++){
 7             for(int j = 0; j < matrix[0].length; j ++){
 8                 if(matrix[i][j] == 0){
 9                     if(sig){
10                         row = i;
11                         col = j;
12                         sig = false;
13                     } else {
14                         matrix[row][j] = 0;
15                         matrix[i][col] = 0;
16                     }
17                 }
18             }
19         }
20         if(sig) return;
21         for(int i = 0; i < matrix.length; i ++){
22             for(int j = 0; j < matrix[0].length; j ++){
23                 if((matrix[row][j] == 0 || matrix[i][col] == 0) && i != row && j != col) matrix[i][j] = 0;
24             }
25         }
26         for(int i = 0; i < matrix.length; i ++){
27             matrix[i][col] = 0;
28         }
29         for(int j = 0; j < matrix[0].length; j ++){
30             matrix[row][j] = 0;
31         }
32     }
33 }

 

Set Matrix Zeroes

标签:style   blog   http   color   io   ar   strong   for   div   

原文地址:http://www.cnblogs.com/reynold-lei/p/3957170.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!