JAVA 6ms Solution, beats 95%


  • 0

    Simple idea: Use recursive approach, each time points to an Integer or Nested List, move to next one until all the elements in current list have been output.

    public class NestedIterator implements Iterator<Integer> {
    
        private List<NestedInteger> nl;
        private int index = 0;
        private Integer next = null;
        private List<NestedInteger> nlNext = null;
        private NestedInteger cur = null;
        private NestedIterator nlNextIter = null;
        
        public NestedIterator(List<NestedInteger> nestedList) {
            nl = nestedList;
            pointToNext();
        }
        private void pointToNext(){
            while(!nl.isEmpty() && index < nl.size()){
                cur = nl.get(index++);
                if(cur.isInteger()){
                    next = cur.getInteger();
                    nlNext = null;
                    break;
                }else{
                    next = null;
                    nlNext = cur.getList();
                    nlNextIter = new NestedIterator(nlNext);
                    if(!nlNextIter.hasNext()){
                        nlNext = null;
                    }
                    else{
                        break;
                    }
                }
            }
        }
    
        @Override
        public Integer next() {
            Integer res = null;
            if(next != null){
                res = next;
                next = null;
                pointToNext();
                return res;
            }
            if(nlNext != null){
                if(nlNextIter.hasNext()){
                    res = nlNextIter.next();
                    if(!nlNextIter.hasNext()){
                        nlNext = null;
                        pointToNext();
                    }
                    return res;
                }
            }
            return res;
        }
    
        @Override
        public boolean hasNext() {
            if(next == null && nlNext == null){
                return false;
            }
            return true;
        }
    }
    

Log in to reply
 

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