简历:The Google Resume: How to Prepare for a Career and Land a Job at Apple, Microsoft, Google, or any Top Tech Company
算法学习书籍:Introduction to Algorithms
编程珠玑:Programming Pearls (2nd Edition)
C++ 学习:The C++ Programming Language, 4th Edition
经典操作系统书籍,龙书:Operating System Concepts
创业:The Start-up of You: Adapt to the Future, Invest in Yourself, and Transform Your Career
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?
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?
这道题不难,不能用additional space,那么用第一行和第一列作为标记的地方。
但是要注意几点:
1. 用bool变量来标记第一行第一列需要不需要set zero,并且最后再做。
2. 在标记完set zero时,不要先动第一行和第一列,不然假如matrix[0][0]==0,那么第一列全set 为 0, 之后的信息就丢失了,所以从1开始set。
请问可否这样做:
ReplyDelete第一次扫描全matrix,如果遇到0就把该行该列设成2,注意这时如果该列/该行有别的元素是0,那不设成2,这样扫描一遍后,就知道凡是2或0的位置就要设成0
第二遍再把它们都设成0
谢谢
如果原本就是2的地方怎么办?
Delete