博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode 251. Flatten 2D Vector
阅读量:4966 次
发布时间:2019-06-12

本文共 2213 字,大约阅读时间需要 7 分钟。

原题链接在这里:

题目:

Implement an iterator to flatten a 2d vector.

Example:

Input: 2d vector =[  [1,2],  [3],  [4,5,6]]Output: [1,2,3,4,5,6]Explanation: By calling next repeatedly until hasNext returns false,              the order of elements returned by next should be: [1,2,3,4,5,6].

Follow up:

As an added challenge, try to code it using only  or .

题解:

用两个index 分别记录list 的 index 和当前 list的element index.

Time Complexity: Vector2D() O(1). hasNext() O(vec2d.size()). next() O(1). Space: O(1).

AC Java:

1 public class Vector2D { 2     List
> listOfList; 3 int listIndex; 4 int elemIndex; 5 public Vector2D(List
> vec2d) { 6 listOfList = vec2d; 7 listIndex = 0; 8 elemIndex = 0; 9 }10 11 public int next() {12 return listOfList.get(listIndex).get(elemIndex++);13 }14 15 public boolean hasNext() {16 while(listIndex < listOfList.size()){17 if(elemIndex < listOfList.get(listIndex).size()){18 return true;19 }else{20 listIndex++;21 elemIndex = 0;22 }23 }24 return false;25 }26 }27 28 /**29 * Your Vector2D object will be instantiated and called as such:30 * Vector2D i = new Vector2D(vec2d);31 * while (i.hasNext()) v[f()] = i.next();32 */

Follow up 要用Iterator class.

Time Complexity:  Vector2D() O(1). hasNext() O(vec2d.size()). next() O(1). Space: O(1).

AC Java:

1 public class Vector2D implements Iterator
{ 2 Iterator
> i; 3 Iterator
j; 4 5 public Vector2D(List
> vec2d) { 6 i = vec2d.iterator(); 7 } 8 9 @Override10 public Integer next() {11 return j.next();12 }13 14 @Override15 public boolean hasNext() {16 while((j==null || !j.hasNext()) && i.hasNext()){17 j = i.next().iterator();18 }19 20 return j!=null && j.hasNext();21 }22 }23 24 /**25 * Your Vector2D object will be instantiated and called as such:26 * Vector2D i = new Vector2D(vec2d);27 * while (i.hasNext()) v[f()] = i.next();28 */

类似.

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/5216481.html

你可能感兴趣的文章
mysql 子查询
查看>>
mysql 自联结
查看>>
mysql union 组合查询
查看>>
socket tcp
查看>>
spiral-matrix-ii &i 生成顺时针序列
查看>>
python set集合方法总结
查看>>
python考点
查看>>
DataMining--Python基础入门
查看>>
单片机复位电路
查看>>
php json_decode失败,返回null
查看>>
获取单选按钮选中的值
查看>>
oracle 分页
查看>>
助教学期总结
查看>>
绘制基本 图形之矩形与多边形
查看>>
3-day3-list-truple-map.py
查看>>
02: djangorestframework使用
查看>>
7zip 自解压安装程序
查看>>
jenkins 离线安装插件 ,插件的下载地址
查看>>
Edit控件显示多行文字
查看>>
java 日期与时间类
查看>>