码迷,mamicode.com
首页 > 编程语言 > 详细

73. Set Matrix Zeroes java solutions

时间:2016-07-05 11:58:29      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:

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?

 

Subscribe to see which companies asked this question

 1 public class Solution {
 2     public void setZeroes(int[][] matrix) {
 3         if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return;
 4         int m = matrix.length, n = matrix[0].length;
 5         int[] rowflag = new int[m];
 6         int[] colflag = new int[n];
 7         for(int i = 0; i < m; i++){
 8             for(int j = 0; j < n; j++){
 9                 if(matrix[i][j] == 0){
10                     rowflag[i] = 1;
11                     colflag[j] = 1;
12                 }
13             }
14         }
15         for(int i = 0; i < m; i++){
16             if(rowflag[i] == 1){
17                 for(int j = 0; j < n; j++){
18                     matrix[i][j] = 0;
19                 }
20             }
21         }
22         for(int i = 0; i < n; i++){
23             if(colflag[i] == 1){
24                 for(int j = 0; j < m; j++){
25                     matrix[j][i] = 0;
26                 }
27             }
28         }
29     }
30 }

 

73. Set Matrix Zeroes java solutions

标签:

原文地址:http://www.cnblogs.com/guoguolan/p/5642756.html

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