Using Queue could solve the problem, why bother using Stack?


  • 0

    Here is my solution using queue, which runs 8ms and beats 85%.

    Algorithm: Use recursion to get an element in the input list and then decode is to a list of integers, then put append the integer to the queue.

    public class NestedIterator implements Iterator<Integer> {
        private Queue<Integer> queue=new LinkedList<>();
        
        public NestedIterator(List<NestedInteger> nestedList) {
            for(NestedInteger ni:nestedList){
                decode(ni);
            }
        }
        
        private void decode(NestedInteger ni){
            if(ni.isInteger()){
                queue.add(ni.getInteger());
            }else{
                List<NestedInteger> inner=ni.getList();
                for(NestedInteger i:inner){
                    decode(i);
                }
            }
        }
    
        @Override
        public Integer next() {
            return queue.poll();
        }
    
        @Override
        public boolean hasNext() {
            return !queue.isEmpty();
        }
    }
    

Log in to reply
 

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