251. Flatten 2D Vector

Design and implement an iterator to flatten a 2d vector. It should support the following operations: next and hasNext.

 

Example:

Vector2D iterator = new Vector2D([[1,2],[3],[4]]);

iterator.next(); // return 1
iterator.next(); // return 2
iterator.next(); // return 3
iterator.hasNext(); // return true
iterator.hasNext(); // return true
iterator.next(); // return 4
iterator.hasNext(); // return false

 

Notes:

  1. Please remember to RESET your class variables declared in Vector2D, as static/class variables are persisted across multiple test cases. Please see here for more details.
  2. You may assume that next() call will always be valid, that is, there will be at least a next element in the 2d vector when next() is called.

 

Follow up:

As an added challenge, try to code it using only iterators in C++ or iterators in Java.

Rust Solution

struct Vector2D {
    array: Vec<i32>,
    count: usize,
}

impl Vector2D {
    fn new(v: Vec<Vec<i32>>) -> Self {
        let mut array = vec![];
        for row in v {
            for col in row {
                array.push(col);
            }
        }
        Vector2D { array, count: 0 }
    }
    fn next(&mut self) -> i32 {
        let res = self.array[self.count];
        self.count += 1;
        res
    }
    fn has_next(&self) -> bool {
        self.count < self.array.len()
    }
}

#[test]
fn test() {
    let v = vec![vec![1, 2], vec![3], vec![4]];
    let mut obj = Vector2D::new(v);
    assert_eq!(obj.next(), 1);
    assert_eq!(obj.next(), 2);
    assert_eq!(obj.next(), 3);
    assert_eq!(obj.has_next(), true);
    assert_eq!(obj.has_next(), true);
    assert_eq!(obj.next(), 4);
    assert_eq!(obj.has_next(), false);
}

Having problems with this solution? Click here to submit an issue on github.