73. 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.
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 not the best solution.
Could you devise a constant space solution?
题意:
给定一个m×n矩阵,如果一个元素为0,则将整个行和列设置为0。在原内存空间上完成。
思路:
利用第一行和第一列做为标志行,先进行遍历,如果存在0,设置标志,最后第一行第一列全部置为0,然后遍历除去第一行和第一列的数组元素,当元素为0时,那么这个元素所在的第一行和第一列最后肯定也置为0,所以直接把元素所在行和列的第一个元素置为0,因为遍历是从第二行和第二列开始的,所以第一行的置0的状态并不影响最后转换的数组状态。
思路的主要点就是利用第一行和第一列做为0元素的标志,重点就是一直到最后才能改变第一行和第一列是否全为0的状态。
1 | class Solution { |
Java Code
1 | class Solution { |