Leetcode: 251. Flatten 2D Vector
Implement an iterator to flatten a 2d vector.
Example 1:
Input: 2d vector =
[
[1,2],
[3],
[4,5,6]
]
Output: [1,2,3,4,5,6]
Explanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,2,3,4,5,6].
Follow up:
As an added challenge, try to code it using only iterators in C++ or iterators in Java.
Solution-1(index):
public class Vector2D implements Iterator {
int indexList, indexElement; //index of lists, and index of element of each list
List> list;
public Vector2D(List> vec2d) { //initialization
indexList = 0;
indexElement = 0;
list = vec2d;
}
@Override
public Integer next() {
return list.get(indexList).get(indexElement++); //get the NEXT element from the list
}
@Override
public boolean hasNext() {
while(indexList
Solution-2(list+iterator):
public class Vector2D implements Iterator {
List vector = new ArrayList<>();
Iterator iter;
public Vector2D(List> vec2d) {
for(List vec1d : vec2d) {
vector.addAll(vec1d);
}
iter = vector.iterator();
}
@Override
public Integer next() {
if(iter.hasNext())
return iter.next();
else
return null;
}
@Override
public boolean hasNext() {
return iter.hasNext();
}
}
Solution-3(iterator+iterator):
public class Vector2D implements Iterator {
private Iterator> i;
private Iterator j;
public Vector2D(List> vec2d) {
i = vec2d.iterator();
}
@Override
public Integer next() {
hasNext(); // important
return j.next();
}
@Override
public boolean hasNext() {
while (i.hasNext() && (j == null || !j.hasNext())) { // tricky
j = i.next().iterator();
}
return j != null && j.hasNext();
}
}
Solution-4(with remove())
class Vector2D implements Iterator {
private int row = 0;
private int col = 0;
private List> vec;
public Vector2D(List> vec2d) {
vec = vec2d;
}
@Override
public Integer next() {
return vec.get(row).get(col++);
}
@Override
public boolean hasNext() {
while(row