Problem
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.
Example 1:
1 |
|
Example 2:
1 |
|
Follow up:
- 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?
Explanation
-
If we want to use O(mn) space, then we can create a new matrix that is same as the input matrix, then we iterate each element of the input matrix, if we find a zero, then we asign zeros to the new matrix’s corresponding row and column.
-
If we want to use O(m+n) space, then we create a one dimensional array that has length m to record which row has zero; and create another one dimensional array that has length n to record which column has zero. At the end, we can update the input matrix’s corresponding row to zero and corresponding column to zero.
-
If we want to use O(1) space, then we cannot create any new array, but we can use the original array’s first row and first column to record each row and each column if they have zero.
- First scan the first row or first column, if first row has zero, then mark zeroRow to true; if first column has zero, then mark zeroColumn to true.
- Then, we scan from the second row and second column, if the element is zero, then we mark its corresponding first row and first column to zero.
- Then, scan again from the second row and second column, if the corresponding first row and first column is zero, then we mark this element to zero.
- At the end, if zeroRow is true, then we make the first row to zero. If zeroColumn is true, then we mark the first column to zero.
Solution
1 |
|