Beat 82% Java recursion solution


  • 0

    Here I flatten all the nested list first, I think other's post which flattens the nested list when we need to is also a good choice, maybe actually a better choice although that seems slower... :)

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

Log in to reply
 

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