Tuesday, September 17, 2013

set matrix zero@leetcode

刷题必备书籍Cracking the Coding Interview: 150 Programming Questions and Solutions 

简历: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?
这道题不难,不能用additional space,那么用第一行和第一列作为标记的地方。
但是要注意几点:
1. 用bool变量来标记第一行第一列需要不需要set zero,并且最后再做。
2. 在标记完set zero时,不要先动第一行和第一列,不然假如matrix[0][0]==0,那么第一列全set 为 0, 之后的信息就丢失了,所以从1开始set。

2 comments:

  1. 请问可否这样做:
    第一次扫描全matrix,如果遇到0就把该行该列设成2,注意这时如果该列/该行有别的元素是0,那不设成2,这样扫描一遍后,就知道凡是2或0的位置就要设成0
    第二遍再把它们都设成0

    谢谢

    ReplyDelete

Leetcode 316. Remove Duplicate Letters

 这道题表面问的是如何删除重复,实际在问如何从多个字符选取一个保留,从而让整个字符串按升序排列。那么策略就是对于高顺位的字符比如‘a',就要选靠前位置的保留,而低顺位字符如’z'则应该尽量选取靠后位置保留。 算法大概思路:每看到一个字符,我们要决定是否保留 1. ...