Set Matrix Zeroes
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 | Input: |
Example 2:
1 | Input: |
Follow up:
- A straight forward solution using O(m**n) 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?
思路:分两部分来做,1. 0行和0列含0时,对应的标志位置为true;
- 将不在0行和0列的为0的元素,移到0行和0列,然后将排除0行和0列之后,对剩下的元素中满足0行或者0列有0元素的行和列全部置为0。
- 最后将对应标志位为true的0行或者0列全部置为0即可。
代码如下:
1 | class Solution { |