Simple Java Solution using a Queue and peek method


  • 0
    S
    public class Vector2D implements Iterator<Integer> {
    
    Queue<Iterator> list = new LinkedList<Iterator>();
    public Vector2D(List<List<Integer>> vec2d) {
        for(List<Integer> row : vec2d) {
            if(!row.isEmpty())
                list.offer(row.iterator());
        }
    }
    
    @Override
    public Integer next() {
        int temp = (int)list.peek().next();
        if(!list.peek().hasNext()) list.poll();
        return temp;
    }
    
    @Override
    public boolean hasNext() {
        return !list.isEmpty(); 
    }
    }

Log in to reply
 

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