Wednesday, August 27, 2014

Set Matrix Zeroes

Problem

Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.

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?

Idea

  • 先扫一边矩阵,然后用数组记录每一行是否有非0元素,再按照数组存储的情况来update矩阵 (可是这个方法需要O(m+n)的空间)
  • 一个更省空间的方法是使用matrix的第一行和第一列来记录该行与该列是否需要被清零。但是首先要扫描第一行与第一列是否要清零,然后当其他行都处理完以后,再回来处理第一行与第一列。

Note

  • 多维vector如何判断行的大小和列的大小

Solution


No comments:

Post a Comment