LeetCode 251: Flatten 2D Vector
Problem Description
Explanation:
To flatten a 2D vector, we can implement an iterator that iterates over each element in the 2D vector in a flattened manner. We can achieve this by using two indices, row
and col
, to keep track of the current position in the 2D vector.
Algorithm:
- Initialize
row
andcol
to 0. - In the
next()
function, return the element atrow
,col
position. - In the
hasNext()
function, check if there are more elements left in the 2D vector. - If
col
reaches the end of the current row, incrementrow
and resetcol
to 0. - Repeat steps 2-4 until all elements are visited.
Time Complexity:
next()
andhasNext()
functions will take O(1) time on average.
Space Complexity:
- O(1) as we are not using any extra data structures. :
Solutions
class Vector2D {
int[][] vec2d;
int row;
int col;
public Vector2D(int[][] vec) {
vec2d = vec;
row = 0;
col = 0;
}
public int next() {
hasNext();
return vec2d[row][col++];
}
public boolean hasNext() {
while (row < vec2d.length && col == vec2d[row].length) {
row++;
col = 0;
}
return row < vec2d.length;
}
}
Related LeetCode Problems
Loading editor...