Simple Java using Queue.


  • 1
    S
    public class Vector2D implements Iterator<Integer> {
        Queue<Iterator> q;
    
        public Vector2D(List<List<Integer>> vec2d) {
            q = new LinkedList<Iterator>();
            for (List<Integer> list : vec2d) {
                q.add(list.iterator());
            }
        }
    
        @Override
        public Integer next() {
            if (hasNext()) {
                Iterator<Integer> it = q.peek();
                return it.next();
            }
            return -1;
            
        }
    
        @Override
        public boolean hasNext() {
            while (!q.isEmpty()) {
                Iterator<Integer> it = q.peek();
                if (it.hasNext()) {
                    return true;
                } else {
                    q.poll();
                }
            }
            return false;
        }
    }
    
    /**
     * Your Vector2D object will be instantiated and called as such:
     * Vector2D i = new Vector2D(vec2d);
     * while (i.hasNext()) v[f()] = i.next();
     */
    
    

Log in to reply
 

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