C++ solution using iterator O(1) Space O(1) Time for each operation


  • 0
    Y
    class ZigzagIterator {
    public:
        ZigzagIterator(vector<int>& v1, vector<int>& v2) {
            tot_cnt = cur_cnt = 0;
            vector<int>::iterator it;
            if(v1.size() != 0){
                tot_cnt += v1.size();
                it = v1.begin();
                vec_it.push_back(it);
                vec_end.push_back(v1.end());
            }
            if(v2.size() != 0){
                tot_cnt += v2.size();
                it = v2.begin();
                vec_it.push_back(it);
                vec_end.push_back(v2.end());
            }
            idx = 0;
        }
    
        int next() {
            int res = *vec_it[idx];
            ++ vec_it[idx];
            ++ cur_cnt;
            int tmp_idx = (idx + 1)%2;
            if(tmp_idx < vec_it.size() && vec_it[tmp_idx] != vec_end[tmp_idx]){
                idx = tmp_idx;
            }
            return res;
        }
    
        bool hasNext() {
            return cur_cnt < tot_cnt;
        }
    private:
    int tot_cnt, cur_cnt;
    vector<vector<int>::iterator> vec_it;
    vector<vector<int>::iterator> vec_end;
    int idx;
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.