[LeetCode][Python]Flatten Nested List Iterator
2016-05-13 16:23
585 查看
Flatten Nested List Iterator
Given a nested list of integers, implement an iterator to flatten it.Each element is either an integer, or a list -- whose elements may also be integers or other lists.
Example 1:
Given the list
[[1,1],2,[1,1]],
By calling next repeatedly until hasNext returns false, the order of elements returned by next should be:
[1,1,2,1,1].
Example 2:
Given the list
[1,[4,[6]]],
By calling next repeatedly until hasNext returns false, the order of elements returned by next should be:
[1,4,6].
https://leetcode.com/problems/flatten-nested-list-iterator/
展平嵌套的list。
从调用的方式来看,总会调用到最后,所以在构造函数中递归展开所有的数放到一位数组中。
另一种方式是把nested list压到栈中,需要的时候再从栈中拿。
注意需要调用注释中的isInteger(),getInteger()和getList()三个方法。
# """ # This is the interface that allows for creating nested lists. # You should not implement it, or speculate about its implementation # """ #class NestedInteger(object): # def isInteger(self): # """ # @return True if this NestedInteger holds a single integer, rather than a nested list. # :rtype bool # """ # # def getInteger(self): # """ # @return the single integer that this NestedInteger holds, if it holds a single integer # Return None if this NestedInteger holds a nested list # :rtype int # """ # # def getList(self): # """ # @return the nested list that this NestedInteger holds, if it holds a nested list # Return None if this NestedInteger holds a single integer # :rtype List[NestedInteger] # """ class NestedIterator(object): def __init__(self, nestedList): """ Initialize your data structure here. :type nestedList: List[NestedInteger] """ self.__list = [] self.__index = 0 self.__getList(nestedList) def __getList(self, nestedList): for item in nestedList: if item.isInteger(): self.__list.append(item.getInteger()) else: self.__getList(item.getList()) def next(self): """ :rtype: int """ res = self.__list[self.__index] self.__index += 1 return res def hasNext(self): """ :rtype: bool """ if(self.__index < len(self.__list)): return True return False
相关文章推荐
- mysql-Python数据库的连接
- python中用的到奇淫技巧
- [Python笔记]第四篇:内置函数
- python合并2个字典
- 【语言-Python】Turtle Screen简单消息处理
- python 线程池
- 极客学院单线程爬虫py3.x版本
- Python实现正则表达式匹配任意的邮箱
- python pymongo
- urllib&urllib2库--python2.X(学习日记2)
- numpy各函数简介之生成数组函数(Array creation routines)
- Eclipse Python开发环境配置(PyDev插件安装)
- python多线程学习
- python对真假的判断方式
- Python3 将configparser从ini文件中读取的内容转换成字典格式
- python里面的函数
- 一个简单的python爬虫程序
- python 判断当前系统的Python编译器类型
- 使用python完成公司考勤数据的邮件发送
- str的format原来是这样用的