题目:

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:

  1. How many variables do you need to keep track?
  2. Two variables is all you need. Try with x and y.
  3. Beware of empty rows. It could be the first few rows.
  4. To write correct code, think about the invariant to maintain. What is it?
  5. 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?
  6. Not sure? Think about how you would implement hasNext(). Which is more complex?
  7. 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.

链接: http://leetcode.com/problems/flatten-2d-vector/

题解:

构造一个2D的iterator。不太理解iterator的原理,第一想法是把vec2d里面的元素都读到Queue里 ,然后再逐个读取。这样的话初始化需要O(n), next和hasNext都为O(1),Space Complexity也是O(n),虽然能ac,但是当vec2d足够大的时候会出问题。

Time Complexity - constructor - O(n),  hasNext - O(1), next() - O(1), Space Complexity - O(n)。

public class Vector2D {
private Queue<Integer> vec1d; public Vector2D(List<List<Integer>> vec2d) {
vec1d = new LinkedList<>();
for(List<Integer> list : vec2d) {
for(int i : list) {
vec1d.offer(i);
}
}
} public int next() {
if(hasNext())
return vec1d.poll();
else
return Integer.MAX_VALUE;
} public boolean hasNext() {
return vec1d.size() > 0;
}
} /**
* Your Vector2D object will be instantiated and called as such:
* Vector2D i = new Vector2D(vec2d);
* while (i.hasNext()) v[f()] = i.next();
*/

Update: 保存两个变量来遍历vec2d

public class Vector2D {
private List<List<Integer>> list;
private int listIndex;
private int elemIndex; public Vector2D(List<List<Integer>> vec2d) {
list = vec2d;
listIndex = 0;
elemIndex = 0;
} public int next() {
return list.get(listIndex).get(elemIndex++);
} public boolean hasNext() {
while(listIndex < list.size()) {
if(elemIndex < list.get(listIndex).size()) {
return true;
} else {
listIndex++;
elemIndex = 0;
}
} return false;
}
} /**
* Your Vector2D object will be instantiated and called as such:
* Vector2D i = new Vector2D(vec2d);
* while (i.hasNext()) v[f()] = i.next();
*/

二刷:

使用了ArrayList的iterator,这个算不算作弊...思路就是,一开始把vec2d里面每个list的iterator都加入到一个iters的ArrayList里。之后就可以很简单地写好hasNext()和next()两个方法了。

Java:

public class Vector2D implements Iterator<Integer> {
private List<Iterator<Integer>> iters;
private int curLine = 0; public Vector2D(List<List<Integer>> vec2d) {
this.iters = new ArrayList<>();
for (List<Integer> list : vec2d) {
iters.add(list.iterator());
}
} @Override
public Integer next() {
return iters.get(curLine).next();
} @Override
public boolean hasNext() {
while (curLine < iters.size()) {
if (iters.get(curLine).hasNext()) return true;
else curLine++;
}
return false;
}
} /**
* Your Vector2D object will be instantiated and called as such:
* Vector2D i = new Vector2D(vec2d);
* while (i.hasNext()) v[f()] = i.next();
*/

Update:

还是使用两个元素来遍历

public class Vector2D implements Iterator<Integer> {
private List<List<Integer>> list;
private int curLine = 0;
private int curElem = 0; public Vector2D(List<List<Integer>> vec2d) {
this.list = vec2d;
} @Override
public Integer next() {
return list.get(curLine).get(curElem++);
} @Override
public boolean hasNext() {
while (curLine < list.size()) {
if (curElem < list.get(curLine).size()) {
return true;
} else {
curLine++;
curElem = 0;
}
}
return false;
}
} /**
* Your Vector2D object will be instantiated and called as such:
* Vector2D i = new Vector2D(vec2d);
* while (i.hasNext()) v[f()] = i.next();
*/

Reference:

http://web.cse.ohio-state.edu/software/2231/web-sw2/extras/slides/17a.Iterators.pdf

http://docs.oracle.com/javase/7/docs/api/

http://stackoverflow.com/questions/21988341/how-to-iterate-through-two-dimensional-arraylist-using-iterator

http://www.cs.cornell.edu/courses/cs211/2005fa/Lectures/L15-Iterators%20&%20Inner%20Classes/L15cs211fa05.pdf

https://leetcode.com/discuss/50292/7-9-lines-added-java-and-c-o-1-space

https://leetcode.com/discuss/55199/pure-iterator-solution-additional-data-structure-list-get

https://leetcode.com/discuss/57984/simple-and-short-java-solution-with-iterator

https://leetcode.com/discuss/50356/my-concise-java-solution

https://leetcode.com/discuss/68860/java-o-1-space-solution

https://leetcode.com/discuss/71002/java-solution-beats-60-10%25

251. Flatten 2D Vector的更多相关文章

  1. 251. Flatten 2D Vector 平铺二维矩阵

    [抄题]: Implement an iterator to flatten a 2d vector. Example: Input: 2d vector = [ [1,2], [3], [4,5,6 ...

  2. LeetCode 251. Flatten 2D Vector

    原题链接在这里:https://leetcode.com/problems/flatten-2d-vector/ 题目: Implement an iterator to flatten a 2d v ...

  3. [LeetCode] 251. Flatten 2D Vector 压平二维向量

    Implement an iterator to flatten a 2d vector. For example,Given 2d vector = [ [1,2], [3], [4,5,6] ] ...

  4. [LeetCode] Flatten 2D Vector 压平二维向量

    Implement an iterator to flatten a 2d vector. For example,Given 2d vector = [ [1,2], [3], [4,5,6] ] ...

  5. Flatten 2D Vector

    Implement an iterator to flatten a 2d vector. For example, Given 2d vector = [ [1,2], [3], [4,5,6] ] ...

  6. LeetCode Flatten 2D Vector

    原题链接在这里:https://leetcode.com/problems/flatten-2d-vector/ 题目: Implement an iterator to flatten a 2d v ...

  7. [Locked] Flatten 2D Vector

    Problem Description: Implement an iterator to flatten a 2d vector. For example,Given 2d vector = [ [ ...

  8. [Swift]LeetCode251.展平二维向量 $ Flatten 2D Vector

    Implement an iterator to flatten a 2d vector. For example,Given 2d vector = [ [1,2], [3], [4,5,6] ] ...

  9. Flatten 2D Vector -- LeetCode

    Implement an iterator to flatten a 2d vector. For example,Given 2d vector = [ [,], [], [,,] ] By cal ...

随机推荐

  1. C程序调用shell脚本共有三种方法

    C程序调用shell脚本共有三种法子 :system().popen().exec系列函数call_exec1.c ,内容为:system() 不用你自己去产生进程,它已经封装了,直接加入自己的命令e ...

  2. JMS之开源实现ActiveMQ

    1.ActiveMQ是开源的JMS实现. 可以把不影响用户执行结果又比较耗时的任务(比如发邮件通知管理员)异步的扔给jms 服务端,而尽快的把屏幕返还给用户,且服务端能够多线程排队响应高并发的请求.可 ...

  3. Java从入门到精通——技巧篇之利用dom4j取出XML文件中的数据

    在我们做项目的时候会经常用到XML文件用来配置系统,XML让系统更加的具有了灵活性,Java如何从XML中取出我们想要的数据呢?下面是我利用DOM4J来实现取出XML文件中的数据. XML文件 < ...

  4. Activity的Launch mode详解 singleTask正解

    Activity有四种加载模式:standard(默认), singleTop, singleTask和 singleInstance.以下逐一举例说明他们的区别: standard:Activity ...

  5. CentOS 6.3 配置 yum

    ContOS 配置yum:1.cd /etc/yum.repos.d2.创建个任意目录,将所有文件移动到创建的目录中,除了CentOS-Media.repo3.编辑CentOS-Media.repov ...

  6. php protected只能被继承,不可以在实例中调用,parent::调用父类(子类函数的重载对父类的函数没有影响)

    <?php class a { private function fun1(){ echo 'a1'; } //protected 可以被继承,但是只能在子类中使用,不能被实例化调用 prote ...

  7. javascript中出现identifier starts immediately after numeric literal错误原因以及解决方法

    javascript遇到参数是字符型和数字型组合的参数就会出现这种错误,例如alert(1);可以正確輸出alert(str);就會報錯alert("str");可以正確輸出.

  8. ubuntu 14.04链接无线路由,建立无线和有线链接

    神奇的linux. 废话不多说,进入主题: 首先1:买一部带wifi的笔记本电脑,买一个可用的无线路由器,像网络提供商申请上网缴费==! 2,中国国情,我们大多都是用ADSL咯.所以其它情况就不说了. ...

  9. cocos2dx中常见的类及类继承关系

    场景:CCScene,继承自CCNode,几乎完全等于CCNode类 CCNode继承自CCObject,CCObject是真正意义上的父类,CCObject又继承自CCCopying类,CCCopy ...

  10. android studio出现 waiting for adb

    cmd进入命令行,进入adb所在的目录下: 出现的鬼异问题如下. C:\Users\xxxx>adb start-server adb server is out of date. killin ...