Sharing my 28ms C++ solution using queue


  • 0
    T
    class ZigzagIterator {
    private:
        queue<int> v;
    public:
        ZigzagIterator(vector<int>& v1, vector<int>& v2) {
            while(v.size()>0)
            {
                v.pop();
            }
            
            int n1 = v1.size();
            int n2 = v2.size();
            int n = min(n1, n2);
            int i;
            for(i=0; i<n; i++)
            {
                v.push(v1[i]);
                v.push(v2[i]);
            }
            
            if(n1>n)
                for(i=n; i<n1; i++)
                    v.push(v1[i]);
            
            else if(n2>n)
                for(i=n; i<n2; i++)
                    v.push(v2[i]);
        }
    
        int next() {
            int result = v.front();
            v.pop();
            return result;
        }
    
        bool hasNext() {
            return (v.size()>0);
        }
    };
    
    /**
     * Your ZigzagIterator object will be instantiated and called as such:
     * ZigzagIterator i(v1, v2);
     * while (i.hasNext()) cout << i.next();
     */

Log in to reply
 

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