Skip to content

Instantly share code, notes, and snippets.

@senthil1216
Created March 5, 2018 02:19
Show Gist options
  • Save senthil1216/9722ffd87fc08c518bb5031aa4d0e4ba to your computer and use it in GitHub Desktop.
Save senthil1216/9722ffd87fc08c518bb5031aa4d0e4ba to your computer and use it in GitHub Desktop.
Flatten 2D vector
import java.util.*;
/*
https://leetcode.com/problems/flatten-2d-vector/description/
Implement an iterator to flatten a 2d vector.
For example,
Given 2d vector =
[
[1,2],
[3],
[4,5,6]
]
By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,2,3,4,5,6].
*/
public class Flatten2DVector implements Iterator<Integer> {
private List<List<Integer>> vector;
private int row, col;
public Flatten2DVector(List<List<Integer>> vec2d) {
vector = vec2d;
row = 0;
col = 0;
}
@Override
public Integer next() {
if (hasNext()) {
Integer curr = vector.get(row).get(col);
col++;
return curr;
}
return null;
}
@Override
public boolean hasNext() {
while (row < vector.size()) {
if (col == vector.get(row).size()) {
col = 0;
row++;
while (row < vector.size() && col < vector.get(row).size()
&& vector.get(row).get(col) == null) {
col++;
}
} else {
return true;
}
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment