[Leetcode] Set Matrix Zeroes

Source: Internet
Author: User

This problem can is solved easily if we is allowed to use more than O (1) space. For example, create a copy of the original matrix (O (MN)-space) or just record the row and column indexes (O (M + N)-space). Well, is there a O (1)-space solution? Yes, refer to this link:-)

The key idea was to record the rows and columns, the need to being set to zeroes directly in the matrix ( if (!ma TRIX[I][J]) matrix[i][0] = matrix[0][j] = 0; ). The code is rewritten as follows.

1 classSolution {2  Public:3     voidSetzeroes (vector<vector<int>>&matrix) {4         intm = Matrix.size (), n = matrix[0].size ();5         BOOLC0 =false;6          for(inti =0; I < m; i++) {7             if(!matrix[i][0]) C0 =true;8              for(intj =1; J < N; J + +)9                 if(!matrix[i][j]) matrix[i][0] = matrix[0][J] =0;Ten         } One          for(inti = m-1; I >=0; i--) { A              for(intj = N-1; J j--) -                 if(!matrix[i][0] || !matrix[0][J]) Matrix[i][j] =0; -             if(C0) matrix[i][0] =0; the         } -     } -};

[Leetcode] Set Matrix Zeroes

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.