281. Zigzag Iterator
2017-01-12 06:31
288 查看
最后更新
二刷
11-Jan-2017
第一种方式是各种pointer标记轮到哪个LIST,在那个LIST是什么index,比较繁琐。
第二种方式是用Queue < List < Integer > >,每次拿出最前面的list,拿出里面的element,然后如果此时list不是空的,从屁眼塞回原来的Queue里。
Time Complexity:
init: O(1)
hasNext: O(1)
next(): O(1)
Space: O(n)
follow up: K lists
没啥变化吧。。按顺序塞屁眼,出来的时候还是这个顺序。
一刷
08-Oct-2017
我是直接按K个来做的,记录总数和已读数量判断hasNext();
一个INDEX,每次mod K得到哪个LIST,/k得到具体INDEX位置,当然如果INDEX位置超过当前LIST的长度,就看下一个LIST。。
Discussion Board提供了用Queue的思路而不用记录INDEX的方法,其实一开始我想到都添加到一个LIST里面,但是会修改原来的LIST,毕竟要删除掉,否则还要记录每个的INDEX,就没意义了。。
下面这个QUEUE是不需要记录INDEX的方法 ..
二刷
11-Jan-2017
第一种方式是各种pointer标记轮到哪个LIST,在那个LIST是什么index,比较繁琐。
第二种方式是用Queue < List < Integer > >,每次拿出最前面的list,拿出里面的element,然后如果此时list不是空的,从屁眼塞回原来的Queue里。
Time Complexity:
init: O(1)
hasNext: O(1)
next(): O(1)
Space: O(n)
public class ZigzagIterator { Queue<List<Integer>> q = new LinkedList<>(); public ZigzagIterator(List<Integer> v1, List<Integer> v2) { if (!v1.isEmpty()) { q.add(v1); } if (!v2.isEmpty()) { q.add(v2); } } public int next() { List<Integer> tempList = q.poll(); int res = tempList.remove(0); if (!tempList.isEmpty()) { q.add(tempList); } return res; } public boolean hasNext() { return !q.isEmpty(); } }
follow up: K lists
没啥变化吧。。按顺序塞屁眼,出来的时候还是这个顺序。
一刷
08-Oct-2017
我是直接按K个来做的,记录总数和已读数量判断hasNext();
一个INDEX,每次mod K得到哪个LIST,/k得到具体INDEX位置,当然如果INDEX位置超过当前LIST的长度,就看下一个LIST。。
public class ZigzagIterator { int total = 0; int cur = 0; int have = 0; List<Integer> l1; List<Integer> l2; public ZigzagIterator(List<Integer> v1, List<Integer> v2) { total = v1.size() + v2.size(); length = Math.max(v1.size(),v2.size())*2; this.l1 = v1; this.l2 = v2; } public int next() { have++; while(true) { if(cur % 2 == 0) { if(cur/2 < l1.size()) { cur++; return l1.get((cur-1)/2); } else cur++; } else { if(cur/2 < l2.size()) { cur++; return l2.get((cur-1)/2); } else cur++; } } } public boolean hasNext() { return (have < total); } }
Discussion Board提供了用Queue的思路而不用记录INDEX的方法,其实一开始我想到都添加到一个LIST里面,但是会修改原来的LIST,毕竟要删除掉,否则还要记录每个的INDEX,就没意义了。。
下面这个QUEUE是不需要记录INDEX的方法 ..
public class ZigzagIterator { Queue<List<Integer>> q = new LinkedList<List<Integer>>(); public ZigzagIterator(List<Integer> v1, List<Integer> v2) { if(!v1.isEmpty()) q.add(v1); if(!v2.isEmpty()) q.add(v2); } public int next() { List<Integer> tempList = q.poll(); int res = tempList.remove(0); if(!tempList.isEmpty()) q.add(tempList); return res; } public boolean hasNext() { return (!q.isEmpty()); } }
相关文章推荐
- Leetcode 447. Number of Boomerangs
- LeetCode Assign Cookies
- 298. Binary Tree Longest Consecutive Sequence
- 计算机网络——介质访问控制子层
- 【数据结构与算法】排序
- 482. License Key Formatting
- exercise 31 做决定
- Elastic Distributed Database
- (未艾原创)当当当当!!!真正的第一篇博文!!Ajax发送请求及处理。(我在新浪博客的第一篇文章)
- exercise 30 else and if 语句
- 双击退出程序
- 设计模式之命令模式(java)
- 361. Bomb Enemy
- exercise 29
- exercise28 布尔运算练习
- 第一次撰写博客——一切的一切才刚刚开始
- exercise 27 记忆逻辑关系
- Mac下安装MySQL(Mac 10.12)
- SpringBoot学习(4) 配置log4j2
- 通过ViewTreeObserver获取View最终的大小及源码分析