Leetcode 251 Solution

This article provides solution to leetcode question 251 (flatten-2d-vector)

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

Solution

class Vector2D {
    queue<pair<vector<int>::iterator, vector<int>::iterator>> q;

public:
    Vector2D(vector<vector<int>>& vec2d) {
        for (auto& vec : vec2d)
            q.push(make_pair(vec.begin(), vec.end()));
    }

    int next() {
        auto& pair = q.front();
        return *pair.first++;
    }

    bool hasNext() {
        while (q.empty() == false)
        {
            auto pair = q.front();
            if (pair.first != pair.second)
                return true;
            q.pop();
        }

        return false;
    }
};

/**
 * Your Vector2D object will be instantiated and called as such:
 * Vector2D i(vec2d);
 * while (i.hasNext()) cout << i.next();
 */