Leetcode Set Matrix Zeroes-----java

Source: Internet
Author: User

Given a m x n Matrix, if an element was 0, set its entire row and column to 0. Do it on 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 is not the best solution.
Could you devise a constant space solution?

Given a m*n matrix, if an element is 0, then the row and column of this element are changed to 0, requiring a space complexity of O (1).

1, the practice of violence is to set up a similar matrix, each encounter 0, and then the second matrix corresponding position 0, the space complexity of O (MN).

2, then a slight optimization is the time each encounter 0, the record needs to set 0 of the line number and column number, the space complexity of O (m+n).

3, if the space complexity is required to 1, in fact, only need to record the method in 2, recorded in the first row and the first column on the line.

 Public classSolution { Public voidSetzeroes (int[] matrix) {        if(Matrix.length = = 0)            return ; intLen1 = matrix.length, len2 = matrix[0].length; BooleanRow0 =false, col0 =false;  for(inti = 0;i<len1;i++){            if(matrix[i][0] = = 0) {col0=true;  Break; }        }             for(inti = 0;i<len2;i++){            if(Matrix[0][i] = = 0) {row0=true;  Break; }        }          for(inti = 0;i<len1;i++){             for(intj = 0;j<len2;j++){                if(Matrix[i][j] = = 0) {matrix[i][0] = 0; matrix[0][J] = 0; }            }        }         for(inti = 1;i<len1;i++){            if(matrix[i][0] = = 0)                 for(intj = 1;j<len2;j++) Matrix[i][j]= 0; }         for(inti = 1;i<len2;i++){            if(Matrix[0][i] = = 0)                 for(intj = 1;j<len1;j++) Matrix[j][i]= 0; }        if(row0) for(inti = 0;i<len2;i++) matrix[0][i] = 0; if(col0) for(inti = 0;i<len1;i++) matrix[i][0] = 0; return ; }}

Leetcode Set Matrix Zeroes-----java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.