0251. Flatten 2D Vector

https://leetcode.com/problems/flatten-2d-vector

Description

Design an iterator to flatten a 2D vector. It should support the next and hasNext operations.

Implement the Vector2D class:

  • Vector2D(int[][] vec) initializes the object with the 2D vector vec.

  • next() returns the next element from the 2D vector and moves the pointer one step forward. You may assume that all the calls to next are valid.

  • hasNext() returns true if there are still some elements in the vector, and false otherwise.

Example 1:

**Input**
["Vector2D", "next", "next", "next", "hasNext", "hasNext", "next", "hasNext"]
[[[[1, 2], [3], [4]]], [], [], [], [], [], [], []]
**Output**
[null, 1, 2, 3, true, true, 4, false]
**Explanation**
Vector2D vector2D = new Vector2D([[1, 2], [3], [4]]);
vector2D.next();    // return 1
vector2D.next();    // return 2
vector2D.next();    // return 3
vector2D.hasNext(); // return True
vector2D.hasNext(); // return True
vector2D.next();    // return 4
vector2D.hasNext(); // return False

Constraints:

  • 0 <= vec.length <= 200

  • 0 <= vec[i].length <= 500

  • -500 <= vec[i][j] <= 500

  • At most 105 calls will be made to next and hasNext.

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

ac

notice: when hasNext() is called, do something, prepare for next() similar: https://leetcode.com/problems/binary-search-tree-iterator/description/

public class Vector2D implements Iterator<Integer> {
    private int list, index;
    private List<List<Integer>> vec;

    public Vector2D(List<List<Integer>> vec2d) {
        list = 0;
        index = 0;
        vec = vec2d;
    }

    @Override
    public Integer next() {
        return vec.get(list).get(index++);
    }

    @Override
    public boolean hasNext() {
        while (list < vec.size()) {
            if (index < vec.get(list).size()) {
                return true;
            } else {
                list++;
                index = 0;
            }
        }
        return false;
    }
}

/**
 * Your Vector2D object will be instantiated and called as such:
 * Vector2D i = new Vector2D(vec2d);
 * while (i.hasNext()) v[f()] = i.next();
 */
public class Vector2D implements Iterator<Integer> {
    private int row, i;
    private List<List<Integer>> list;

    public Vector2D(List<List<Integer>> vec2d) {
        row = 0;
        i = 0;
        list = vec2d;
    }

    @Override
    public Integer next() {
        return hasNext() ? list.get(row).get(i++) : null;
    }

    @Override
    public boolean hasNext() {
        while (row < list.size() && i == list.get(row).size()) {
            row++;
            i = 0;
        }

        return row < list.size() && i < list.get(row).size();
    }
}

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

Last updated