Set Matrix Zeroes, Leetcode 解题笔记

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?

前面O(mn)和O(m+n)的方法都非常简单,这里直接说constant space。
方法真是非常巧妙:
1.先确定第一行和第一列是否需要清零
2.扫描剩下的矩阵元素,如果遇到了0,就将对应的第一行和第一列上的元素赋值为0
3.根据第一行和第一列的信息,已经可以讲剩下的矩阵元素赋值为结果所需的值了
4.根据1中确定的状态,处理第一行和第一列。

public class Solution {
    public void setZeroes(int[][] matrix) {
        boolean rf = false;
        boolean cf = false;
        
        int ln = matrix.length;
        int en = matrix[0].length;
        
        for(int i = 0; i < ln; i++){
            if(matrix[i][0] == 0){
                rf = true;
            }
        }
        
        for(int i = 0; i < en; i++){
            if(matrix[0][i] == 0){
                cf = true;
            }
        }
        
        for(int i = 1; i < ln; i++){
            for(int j = 0; j < en; j++){
                if(matrix[i][j] == 0){
                    matrix[i][0] = 0;
                    matrix[0][j] = 0;
                }
            }
        }
        
        for(int i = 1; i < ln; i++){
            if(matrix[i][0] == 0){
                for(int j = 0; j < en; j++){
                    matrix[i][j] = 0;
                }
            }
        }
        
        for(int i = 0; i < en; i++){
            if(matrix[0][i] == 0){
                for(int j = 0; j < ln; j++){
                    matrix[j][i] = 0;
                }
            }
        }
        
        if(rf == true){
            for(int j = 0; j < ln; j++){
                    matrix[j][0] = 0;
            }
        }
        
        if(cf == true){
            for(int j = 0; j < en; j++){
                    matrix[0][j] = 0;
            }
        }
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s