Set Matrix Zeroes Java Solutions

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?

Subscribe to see which companies asked this question

1  Public classSolution {2      Public voidSetzeroes (int[] matrix) {3         if(Matrix = =NULL|| Matrix.length = = 0 | | Matrix[0].length = = 0)return;4         intm = matrix.length, n = matrix[0].length;5         int[] Rowflag =New int[m];6         int[] Colflag =New int[n];7          for(inti = 0; I < m; i++){8              for(intj = 0; J < N; J + +){9                 if(Matrix[i][j] = = 0){TenRowflag[i] = 1; OneCOLFLAG[J] = 1; A                 } -             } -         } the          for(inti = 0; I < m; i++){ -             if(Rowflag[i] = = 1){ -                  for(intj = 0; J < N; J + +){ -MATRIX[I][J] = 0; +                 } -             } +         } A          for(inti = 0; I < n; i++){ at             if(Colflag[i] = = 1){ -                  for(intj = 0; J < M; J + +){ -Matrix[j][i] = 0; -                 } -             } -         } in     } -}

Set Matrix Zeroes Java Solutions

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.