[LeetCode] 251. Flatten 2D Vector

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].
Follow up:
As an added challenge, try to code it using only iterators in C++ or iterators in Java.

Thought process:
Use two iterators. One to iterate through rows. The other to iterate through columns. 

Solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class Vector2D implements Iterator<Integer> {
    private Iterator<List<Integer>> row;
    private Iterator<Integer> column;

    public Vector2D(List<List<Integer>> vec2d) {
        this.row = vec2d.iterator();
    }

    @Override
    public Integer next() {
        this.hasNext();
        return column.next();
    }

    @Override
    public boolean hasNext() {
        while ((column == null || !column.hasNext()) && row.hasNext()) {
            column = row.next().iterator();
        }
        return column != null && column.hasNext();
    }
}

/**
 * Your Vector2D object will be instantiated and called as such:
 * Vector2D i = new Vector2D(vec2d);
 * while (i.hasNext()) v[f()] = i.next();
 */

Time complexity: both O(1).

Comments

Popular posts from this blog

[LeetCode] 631. Design Excel Sum Formula

[LeetCode] 714. Best Time to Buy and Sell Stock with Transaction Fee

[LeetCode] 269. Alien Dictionary