您的位置:首页 > 其它

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)

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());
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: