HoppingIterator

 

/**
* Implement an iterator that hops specified number of times and then returns the next. 
* element after the hop. Note: the iterator always returns the first element as 
* it is, and starts hopping only after the first element.. more info on 1point3acres.com
*
* Examples:
*
* If the original iterator returns: [1, 2, 3, 4, 5] in order, then the hopping
* iterator will return [1, 3, 5] in order when the hop value is 1.
*
* If the original iterator returns: [1, 2, 3, 4, 5] in order, then the hopping. 
* iterator will return [1, 4] in order when the hop value is 2. 
*
* If the original iterator returns: [1, 2, 3, 4, 5] in order, then the hopping
* iterator will return [1, 5] in order when the hop value is 3.. 
* 
* Methods expected to be implemented:
* 
* public class HoppingIterator<T> implements Iterator<T> {
*                 public HoppingIterator(Iterator<T> iterator, int numHops) {...}
*                 public boolean hasNext() {...}. more info on 1point3acres.com
*                 public T next() {...}
* }
*/

 第一道是设计一个有选择性的iterator,类型T。面试官给的API里有一个自定selector,selector里有差不多叫boolean isOK(T t)方法。设计一个iterator每次调用hasNext(),返回接下来是否能取到合格的T对象;每次调用next(),返回下一个合格的T对象。我用buffer做的。
第二道是设计一个展开nested对象的iterator,面试后有小伙伴说某扣有类似题341,但不在L家tag下,大家可以参考一下。有蛮多改动,类型不是Nested Integer而是一个Data<T>。Data也是自己定义的API,当时面试时间短看两大页的API已经看晕了非常恐惧,有点没记住API细节了。一开始我想说用Stack<Integer>存储访问到的对象在Collection里的下标,讨论了蛮久,后来面试官说不行因为这个Collection里没有get(i)方法,下标调用不到。最后我请求给答案面试官说用Stack<Iterator>,这个我真是有点没有想到

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;


public class HoppingIterator<T> implements Iterator<T>{
	public T next = null;
	public int hop;
	public Iterator<T> buffer;
		
	public HoppingIterator(Iterator<T> iterator, int numHops) {
		this.hop = numHops;
		this.buffer = iterator;
		if (buffer.hasNext()) {
			next = buffer.next();
		}
	}
	
	public boolean hasNext() {
		return next != null;
	}
	
	public T next() {
		T rs = next;
		for (int i = 0 ; i <= hop; i++) {
			if (buffer.hasNext()) {
				next = buffer.next();
			} else {
				next = null;
				break;
			}
		}
		return rs;
	}

	@Override
	public void remove() {
		// TODO Auto-generated method stub
		
	}
	
	public static void main(String[] args) {
		Integer[] a = {1, 2, 3, 4, 5};
		List<Integer> k = Arrays.asList(a);
		HoppingIterator<Integer> hp = new HoppingIterator<>(k.iterator(), 2);
		while (hp.hasNext()) {
			System.out.println(hp.next());
		}
	}
	
}

  

posted @ 2017-12-03 02:20  apanda009  阅读(170)  评论(0编辑  收藏  举报