Lazy loading iterator - Java(Queue) based solution - beat 89% of solution


  • 0
    C
    
            List<NestedInteger> inputList;
            //Queue to flatten the next element
            Deque<Integer> queue = new LinkedList<>();
            int pos=0;
    
            public NestedIterator(List<NestedInteger> nestedList) {
                this.inputList = nestedList;
            }
    
            @Override
            public Integer next() {
                //return the first element from the queue
                return queue.poll();
            }
    
            @Override
            public boolean hasNext() {
                if(!queue.isEmpty()){
                    return true;
                }
                //Queue is empty but pos can still load more elements from the array
                else if(pos < inputList.size()){
                    flatten(inputList,inputList.get(pos++),queue);
                    if(!queue.isEmpty()){
                        return true;
                    }
                }
                return false;
            }
    
            public void flatten(List<NestedInteger> list, NestedInteger curr, Deque<Integer> queue){
                if(!curr.isInteger()){
                    if(curr.getList().size() > 0){
                        for(NestedInteger nested:curr.getList()){
                            if(!nested.isInteger()){
                                //of its a list size() =>1 - Now flatten
                                flatten(list,nested,queue);
                            }
                            else{
                                if(nested.getInteger() != null){
                                    queue.addLast(nested.getInteger());
                                }
                            }
                        }
                    }
                    //check if pos has more elements and if so flatten into Queue
                    if(pos < inputList.size() && queue.isEmpty())
                        flatten(list,inputList.get(pos++),queue);
    
                }else{
                    if(curr.getInteger() != null){
                        queue.addLast(curr.getInteger());
                    }
                    return;
                }
            }
        }
    

Log in to reply
 

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