边工作边刷题:70天一遍leetcode: day 84
Flatten 2D Vector
要点:
- 这题是2d的iterator,一般对于1d的情况,hasNext()是不需要做移动的。而2d不同,core iterator是j向的,而i向要在hasNext()中移动以保证call next()的时候j是available的。
 - hasNext()如何移动?首先的思路是not j.hasNext()是触发i移动的条件,同时j本身也可能是None(比如Null 2d list)。简单的说就是不算移动i直到j没超界,如果i都超界了,那么return False. 这个条件下还要判断i.hasNext(),然后移动i,赋值j iterator。当这步之后还是not j.hasNext()。那么说明遍历完毕。
 - 同样这题无论是用iterator还是index都是同样思路,index的时候hasNext()要先判断i,然后才有机会判断j。而iterator version,一个0元素list仍然有iterator,但是i.hasNext()为False。用j iterator为None来表示i根本没初始化
 
# Implement an iterator to flatten a 2d vector.
# For example,
# Given 2d vector =
# [
#   [1,2],
#   [3],
#   [4,5,6]
# ]
# By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,2,3,4,5,6].
# Hint:
# How many variables do you need to keep track?
# Two variables is all you need. Try with x and y.
# Beware of empty rows. It could be the first few rows.
# To write correct code, think about the invariant to maintain. What is it?
# The invariant is x and y must always point to a valid point in the 2d vector. Should you maintain your invariant ahead of time or right when you need it?
# Not sure? Think about how you would implement hasNext(). Which is more complex?
# Common logic in two different places should be refactored into a common method.
# Follow up:
# As an added challenge, try to code it using only iterators in C++ or iterators in Java.
# Hide Company Tags Google Airbnb Twitter Zenefits
# Hide Tags Design
# Hide Similar Problems (M) Binary Search Tree Iterator (M) Zigzag Iterator (M) Peeking Iterator (M) Flatten Nested List Iterator
class Vector2D(object):
    def __init__(self, vec2d):
        """
        Initialize your data structure here.
        :type vec2d: List[List[int]]
        """
        self.vec = vec2d
        self.i = 0
        self.j = 0
    def next(self):
        """
        :rtype: int
        """
        ret = self.vec[self.i][self.j]
        self.j+=1
        return ret
    def hasNext(self):
        """
        :rtype: bool
        """
        while self.i<len(self.vec):
            if self.j<len(self.vec[self.i]):
                return True
            self.i+=1
            self.j=0
        return False
# Your Vector2D object will be instantiated and called as such:
# i, v = Vector2D(vec2d), []
# while i.hasNext(): v.append(i.next())
												
											边工作边刷题:70天一遍leetcode: day 84的更多相关文章
- 边工作边刷题:70天一遍leetcode: day 89
		
Word Break I/II 现在看都是小case题了,一遍过了.注意这题不是np complete,dp解的time complexity可以是O(n^2) or O(nm) (取决于inner ...
 - 边工作边刷题:70天一遍leetcode: day 77
		
Paint House I/II 要点:这题要区分房子编号i和颜色编号k:目标是某个颜色,所以min的list是上一个房子编号中所有其他颜色+当前颜色的cost https://repl.it/Chw ...
 - 边工作边刷题:70天一遍leetcode: day 78
		
Graph Valid Tree 要点:本身题不难,关键是这题涉及几道关联题目,要清楚之间的差别和关联才能解类似题:isTree就比isCycle多了检查连通性,所以这一系列题从结构上分以下三部分 g ...
 - 边工作边刷题:70天一遍leetcode: day 85-3
		
Zigzag Iterator 要点: 实际不是zigzag而是纵向访问 这题可以扩展到k个list,也可以扩展到只给iterator而不给list.结构上没什么区别,iterator的hasNext ...
 - 边工作边刷题:70天一遍leetcode: day 101
		
dp/recursion的方式和是不是game无关,和game本身的规则有关:flip game不累加值,只需要一个boolean就可以.coin in a line II是从一个方向上选取,所以1d ...
 - 边工作边刷题:70天一遍leetcode: day 1
		
(今日完成:Two Sum, Add Two Numbers, Longest Substring Without Repeating Characters, Median of Two Sorted ...
 - 边工作边刷题:70天一遍leetcode: day 70
		
Design Phone Directory 要点:坑爹的一题,扩展的话类似LRU,但是本题的accept解直接一个set搞定 https://repl.it/Cu0j # Design a Phon ...
 - 边工作边刷题:70天一遍leetcode: day 71-3
		
Two Sum I/II/III 要点:都是简单题,III就要注意如果value-num==num的情况,所以要count,并且count>1 https://repl.it/CrZG 错误点: ...
 - 边工作边刷题:70天一遍leetcode: day 71-2
		
One Edit Distance 要点:有两种解法要考虑:已知长度和未知长度(比如只给个iterator) 已知长度:最好不要用if/else在最外面分情况,而是loop在外,用err记录misma ...
 
随机推荐
- python-set集合类方法
			
s1=set([11,22,33,44,'Tom','tony',11,77,2.5,])返回的是{11,22,33,44,'Tom','tony',77,2.5}(注意:返回的并不是一个字典,只是告 ...
 - 泛函编程(12)-数据流-Stream
			
在前面的章节中我们介绍了List,也讨论了List的数据结构和操作函数.List这个东西从外表看上去挺美,但在现实中使用起来却可能很不实在.为什么?有两方面:其一,我们可以发现所有List的操作都是在 ...
 - 类库LinqToExcel的介绍
			
LinqToExcel是一个.net framework平台下开源项目,它主要实现了LINQ的语法查询Excel电子表格.类型之前的LINQToXXX如果你是LINQ语法糖爱好者那最适 ...
 - ASP.NET Core 1.0开发Web API程序
			
.NET Core版本:1.0.0-rc2Visual Studio版本:Microsoft Visual Studio Community 2015 Update 2开发及运行平台:Windows ...
 - 依赖于spring 4.x的spring组件
			
1.Spring Data MongoDB 1.6.x开始依赖于spring 4.x: 2.@Conditional注解: 3.spring-data-redis 1.4.x开始依赖于spring 4 ...
 - linux线程控制&线程分离
			
线程概念 线程,有时被称为轻量级进程(Lightweight Process,LWP),是程序执行流的最小单元. 线程是程序中一个单一的顺序控制流程.进程内一个相对独立的.可调度的执行单元,是系统独立 ...
 - 关于使用ResultSet ---结果集没有当前行
			
Resultset返回的结果集是从结果的前一句开始的,也就是说一开始的resultset是没有的,所以,一般使用的时候,需要这样子写: while( resultSet.next() ){ ...
 - ng-show
			
//当ng-show="false"时,自动添加 #animate.ng-hide { } #animate.ng-hide-add { } #animate.ng-hide-ad ...
 - 利用ng-click、ng-switch和click-class制作切换的tabl
			
效果如下图,当分别点击1,2,3时,下面的不同颜色的div会切换 <html ng-app> <head> <title></title> <sc ...
 - Office 365 - SharePoint 2013 Online 之母版页和页面布局
			
1.打开https://login.microsoftonline.com,登陆,点击SharePoint,如下图: 2.打开网站集,可以查看.添加.删除等管理操作: 3.打开一个站点,如下图: 4. ...