7ms java solution


  • 2
    D
    private List<Integer> nestedList = new ArrayList<>();
    private int index;
    
    private static void buildList(List<Integer> list, List<NestedInteger> nestedList) {
        for (NestedInteger nestedInteger : nestedList) {
            if (nestedInteger.isInteger()) list.add(nestedInteger.getInteger());
            else buildList(list, nestedInteger.getList());
        }
    }
    
    public NestedIterator(List<NestedInteger> nestedList) {
        buildList(this.nestedList, nestedList);
    }
    
    @Override
    public Integer next() {
        return nestedList.get(index++);
    }
    
    @Override
    public boolean hasNext() {
        return nestedList.size() != index;
    }

  • 0
    D

    Nice one. I took a similar approach but use queue as my internal storage structure.

    public class NestedIterator implements Iterator<Integer> {
    private Queue<Integer> queue;

    public NestedIterator(List<NestedInteger> nestedList) {
        queue = new ArrayDeque<Integer>();
        traverse(nestedList);
    }
    
    private void traverse(List<NestedInteger> nestedList){
        for(NestedInteger node : nestedList){
            if(node.isInteger()){ 
                queue.add(node.getInteger());
            }else{
                traverse(node.getList());
            }
        }
    }
    
    @Override
    public Integer next() {
        return queue.poll();
    }
    
    @Override
    public boolean hasNext() {
        return queue.peek() != null;
    }
    

    }


  • 0
    I

    @danielchang1991 I used queue either, and I think queue and dfs is more intuitive for this one.


Log in to reply
 

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