首页 > 其他 > 详细

[LeetCode]Set Matrix Zeroes

时间:2015-04-06 15:42:02      阅读:172      评论: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.
in place,主要是感觉比较麻烦,其实就是利用第一行和第一列保存该行列是否需要变0,再用两个变量表示第一行和第一列是否需要变0
代码:
public class Solution {
    public void setZeroes(int[][] matrix) {
        int m = matrix.length, n = matrix[0].length;
        boolean colZero = false;
        boolean rowZero =false;
        for(int i = 0; i < m; ++i){
            for(int j = 0; j < n; ++ j){
                if(matrix[i][j] == 0){
                    if(i == 0) rowZero = true;
                    if(j == 0) colZero = true;
                    matrix[i][0] = 0;
                    matrix[0][j] = 0;
                }
            }
        }
        for(int j =1; j < n; ++ j){
            if(matrix[0][j] == 0){
                for (int i = 0; i < m; ++i){
                    matrix[i][j] = 0;
                }
            }
        }

        for(int i =1; i < m; ++ i){
            if(matrix[i][0] == 0){
                for (int j = 0; j < n; ++j){
                    matrix[i][j] = 0;
                }
            }
        }
        if(colZero){
            for(int i = 0; i< m; ++i){
                matrix[i][0] = 0;
            }
        }
        
        if(rowZero){
            for (int j = 0 ; j< n; ++j){
                matrix[0][j] = 0;
            }
        }

    }

}
此外我们可以记录相应的0的位置,我这其实是浪费空间了,其实可以优化到O(m+n)的空间
    public void setZeroes1(int[][] matrix) {
        int m = matrix.length, n = matrix[0].length;
        class Node {
            int x;
            int y;

            public Node(int x, int y) {
                this.x = x;
                this.y = y;
            }
        }
        List<Node> nodes = new LinkedList<Node>();
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (matrix[i][j] == 0) {
                    nodes.add(new Node(i, j));
                }
            }
        }
        for (Node node : nodes) {
            for (int i = 0; i < m; i++) {
                matrix[i][node.y] = 0;
            }
            for (int j = 0; j < n; ++j) {
                matrix[node.x][j] = 0;
            }
        }
    }




[LeetCode]Set Matrix Zeroes

原文:http://blog.csdn.net/youmengjiuzhuiba/article/details/44902431

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!