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<Integer> {
int indexList, indexElement; //index of lists, and index of element of each list
List<List<Integer>> list;
public Vector2D(List<List<Integer>> 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<list.size()){ //loop into lists, not reach the end of lists
if(indexElement<list.get(indexList).size()){ //loop into the list, not reach the end of the list
return true;
}
else{ //reached end of the list, move to the next list, and move the index of the element to the beginning
indexList++;
indexElement = 0;
}
}
return false;
}
}
Solution-2(list+iterator):
public class Vector2D implements Iterator<Integer> {
List<Integer> vector = new ArrayList<>();
Iterator<Integer> iter;
public Vector2D(List<List<Integer>> vec2d) {
for(List<Integer> 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<Integer> {
private Iterator<List<Integer>> i;
private Iterator<Integer> j;
public Vector2D(List<List<Integer>> 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<Integer> {
private int row = 0;
private int col = 0;
private List<List<Integer>> vec;
public Vector2D(List<List<Integer>> vec2d) {
vec = vec2d;
}
@Override
public Integer next() {
return vec.get(row).get(col++);
}
@Override
public boolean hasNext() {
while(row<vec.size() && col==vec.get(row).size()) {
col = 0;
row++;
}
return !(row==vec.size());
}
@Override
public void remove() {
vec.get(row).remove(col--);
}
}
网友评论