Wednesday, September 30, 2020

L 281. Zigzag Iterator ----M ~~~~!!!!

 Given two 1d vectors, implement an iterator to return their elements alternately.

 

Example:

Input:
v1 = [1,2]
v2 = [3,4,5,6] 
Output: [1,3,2,4,5,6]
Explanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,3,2,4,5,6].

 

Follow up:

What if you are given k 1d vectors? How well can your code be extended to such cases?

Clarification for the follow up question:
The "Zigzag" order is not clearly defined and is ambiguous for k > 2 cases. If "Zigzag" does not look right to you, replace "Zigzag" with "Cyclic". For example:

Input:
[1,2,3]
[4,5,6,7]
[8,9]

Output: [1,4,8,2,5,9,3,6,7].

A:

这里,最先错的地方,就是 iterator, 不需要拷贝原有内容的。

这个比较傻逼。是因为自己以前没有看过真正的代码实现。

class ZigzagIterator {
public:
    ZigzagIterator(vector<int>& v1, vector<int>& v2) {
        s1 = v1.begin();
        s2 = v2.begin();
        e1 = v1.end();
        e2 = v2.end();
        isFirst = true;        
    }

    int next() {        
        int res=0;
        if(s1==e1){
            res = *s2;
            s2++;
        }else if(s2==e2){
            res = *s1;
            s1++;
        }else{
            if(isFirst){                
                res = *s1;
                isFirst = ! isFirst;
                s1++;
            }else{
                res = *s2;
                isFirst = ! isFirst;
                s2++;
            }
        }
        return res;
    }

    bool hasNext() {
        return s1 !=e1 ||  s2 != e2;
    }
private:
    vector<int>::iterator s1,s2,e1,e2;
    bool isFirst;
};

/**
 * Your ZigzagIterator object will be instantiated and called as such:
 * ZigzagIterator i(v1, v2);
 * while (i.hasNext()) cout << i.next();
 */






No comments:

Post a Comment