本文主要是介绍Zigzag Iterator ii,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
//23. Zigzag Iterator/*
Given two 1d vectors, implement an iterator to return their elements alternately.
v1 = [1, 2]
v2 = [3, 4, 5, 6]
v = [1, 3, 2, 4, 5, 6]
*/
/*
解题思路: 实现Iterator的问题是现在面试中一个非常常见的问题,在这个题目中需要借助List的本身自带的
Iterator的方法,进行实现。
*/
public class ZigzagIterator {/** @param v1: A 1d vector* @param v2: A 1d vector*/Iterator<Integer> it1;Iterator<Integer> it2;int turn;public ZigzagIterator(List<Integer> v1, List<Integer> v2) {// do intialization if necessaryit1 = v1.iterator();it2 = v2.iterator();turn = 0;}/** @return: An integer*/public int next() {// write your code hereint val = 0;if ((turn % 2 == 0 && it1.hasNext()) || (it1.hasNext() && !it2.hasNext())) {val = it1.next();} else if ((turn % 2 == 1 && it2.hasNext()) || (it2.hasNext() && !it1.hasNext())) {val = it2.next();}turn++;return val;}/** @return: True if has next*/public boolean hasNext() {// write your code herereturn it1.hasNext() || it2.hasNext();}
}/*** Your ZigzagIterator object will be instantiated and called as such:* ZigzagIterator solution = new ZigzagIterator(v1, v2);* while (solution.hasNext()) result.add(solution.next());* Output result*/
follow up:
Follow up Zigzag Iterator: What if you are given k
1d vectors? How well can your code be extended to such cases? The "Zigzag" order is not clearly defined and is ambiguous for k > 2
cases. If "Zigzag" does not look right to you, replace "Zigzag" with "Cyclic".
Given k = 3
1d vectors:
[1,2,3]
[4,5,6,7]
[8,9]
Return [1,4,8,2,5,9,3,6,7]
.
// 解题思路:还是使用Iterator的方法进行处理,设定一个Iterator数组,不断向里面加入数据然后一旦数据
// 使用完毕,就将该iterator删除
public class ZigzagIterator2 {/** @param vecs: a list of 1d vectors*/List<Iterator<Integer>> path;int turn;public ZigzagIterator2(List<List<Integer>> vecs) {// do intialization if necessarypath = new ArrayList<Iterator<Integer>>();for (List<Integer> vec : vecs) {if (vec.size() > 0) {path.add(vec.iterator());}}turn = 0;}/** @return: An integer*/public int next() {// write your code hereint val = path.get(turn).next();if (path.get(turn).hasNext()) {turn = (turn + 1) % path.size();} else {path.remove(turn);if (path.size() > 0) {turn %= path.size(); }}return val;}/** @return: True if has next*/public boolean hasNext() {// write your code herereturn path.size() > 0;}
}
这篇关于Zigzag Iterator ii的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!