251. Flatten 2D Vector 平铺二维矩阵
Design and implement an iterator to flatten a 2d vector. It should support the following operations: next
and hasNext
.
Example:Vector2D iterator = new Vector2D([[1,2],[3],[4]]);
iterator.next(); // return 1
iterator.next(); // return 2
iterator.next(); // return 3
iterator.hasNext(); // return true
iterator.hasNext(); // return true
iterator.next(); // return 4
iterator.hasNext(); // return false
思路:
不懂为啥要用两个iter,只有一个不行吗?
这样就没有实现2D变1D的过程,所以需要有两个iter。但是判断、取出下一个元素都是根据colIter来的
colIter = Arrays.stream(rowIter.next()).iterator();
等于null是真没了,和hashNext是两个概念
class Vector2D { //声明就行了 private Iterator<int[]> rowIter; private Iterator<Integer> colIter; public Vector2D(int[][] v) { rowIter = Arrays.stream(v).iterator(); if(rowIter.hasNext()) colIter = Arrays.stream(rowIter.next()).iterator(); } //返回colIter的下一个 public int next() { if(!colIter.hasNext()) return -1; return colIter.next(); } //判断colIter是否有下一个元素 public boolean hasNext() { //等于null是真没了,和hashNext是两个概念 if(colIter == null) return false; while(!colIter.hasNext() && rowIter.hasNext()) colIter = Arrays.stream(rowIter.next()).iterator(); return colIter.hasNext(); } }