LeetCode Flatten 2D Vector
2016-02-25 11:48
363 查看
原题链接在这里:https://leetcode.com/problems/flatten-2d-vector/
题目:
Implement an iterator to flatten a 2d vector.
For example,
Given 2d vector =
By calling next repeatedly until hasNext returns false, the order of elements returned by next should be:
题解:
用两个index 分别记录list 的 index 和当前 list的element index.
Time Complexity: Vector2D() O(1). hasNext() O(1). next(1). Space: O(1).
AC Java:
题目:
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].
题解:
用两个index 分别记录list 的 index 和当前 list的element index.
Time Complexity: Vector2D() O(1). hasNext() O(1). next(1). Space: O(1).
AC Java:
public class Vector2D { List<List<Integer>> listOfList; int listIndex; int elemIndex; public Vector2D(List<List<Integer>> vec2d) { listOfList = vec2d; listIndex = 0; elemIndex = 0; } public int next() { return listOfList.get(listIndex).get(elemIndex++); } public boolean hasNext() { while(listIndex < listOfList.size()){ if(elemIndex < listOfList.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(); */
相关文章推荐
- 一个优秀的Android应用从建项目开始
- php课程---Json格式规范需要注意的小细节
- Oracle数据库如何创建Database Link呢
- 使用 Java8 实现观察者模式的方法(下)
- squid
- Java修饰符关键词大全
- 统计学习
- I/O Stream
- HDU 3698 DP+线段树
- Java项目导出war包 security alert:integrity check error”
- php文件操作
- vsftp
- linux磁盘分区一些细节
- Java 动态代理
- Javascript变量的命名规则
- Android应用开发中Fragment的静态加载与动态加载实例
- 10个影响JavaEE性能问题
- HDU 5625 Clarke and chemistry(字符串模拟题目)
- Windows7下如何删除cygwin 文件夹
- Android检测网络是否正常代码!