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

Set Matrix Zeroes

时间:2014-09-19 10:10:15      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:style   color   io   java   ar   strong   for   div   sp   

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(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?

答案

public class Solution {
    public void setZeroes(int[][] matrix) {
        if(matrix==null||matrix.length<=0||matrix[0].length<=0)
        {
            return;
        }
        LinkedList<Integer> ROW=new LinkedList<Integer>();
        LinkedList<Integer> COL=new LinkedList<Integer>();
        for(int row=0;row<matrix.length;row++)
        {
            for(int col=0;col<matrix[row].length;col++)
            {
                if(matrix[row][col]==0)
                {
                    ROW.add(row);
                    COL.add(col);
                }
            }
        }
        for(int row:ROW)
        {
            for(int col=0;col<matrix[row].length;col++)
            {
               matrix[row][col]=0;
            }
        }
        for(int col:COL)
        {
            for(int row=0;row<matrix.length;row++)
            {
               matrix[row][col]=0;
            }
        }
    }
}


Set Matrix Zeroes

标签:style   color   io   java   ar   strong   for   div   sp   

原文地址:http://blog.csdn.net/jiewuyou/article/details/39393965

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