Java list and index version - beat 96% solutions


  • 0
    L

    The basic idea is to use a list to store all integers, and use an index to maintain the position of the current iteration.

    public class NestedIterator implements Iterator<Integer> {
    
        private int index = 0;
        private List<Integer> intList;
        public NestedIterator(List<NestedInteger> nestedList) {
            intList = new ArrayList<Integer>();
            buildIntegerList(nestedList, intList);
        }
        
        private void buildIntegerList(List<NestedInteger> nestedList, List<Integer> intList) {
            for(NestedInteger list : nestedList) {
                if(list.isInteger()) {
                    intList.add(list.getInteger());
                }
                else {
                    buildIntegerList(list.getList(), intList);
                }
            }
        }
    
        @Override
        public Integer next() {
            return intList.get(index++);
        }
    
        @Override
        public boolean hasNext() {
            return (index < intList.size());
        }
    }

Log in to reply
 

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