Sunday, August 20, 2017

341. Flatten Nested List Iterator

"In the constructor, we push all the nestedList into the stack from back to front, so when we pop the stack, it returns the very first element. Second, in the hasNext() function, we peek the first element in stack currently, and if it is an Integer, we will return true and pop the element. If it is a list, we will further flatten it. This is iterative version of flatting the nested list. Again, we need to iterate from the back to front of the list."

这里我用了一个全局的Next变量cache了hasNext里面的top值

上面的explaination里面用peek() 代替了pop(),在next()里面才pop(),比我写的好一些

43.94 % 
public class NestedIterator implements Iterator<Integer> {
    // Tree in-order traversal
    Stack<NestedInteger> stack = new Stack<>();
    Integer next;
    public NestedIterator(List<NestedInteger> nestedList) {
        for (int i = nestedList.size() - 1; i >= 0; i--) {
            stack.push(nestedList.get(i));
        }
    }

    @Override
    public Integer next() {
       return next;
    }

    @Override
    public boolean hasNext() {
        NestedInteger curr;
        while (!stack.isEmpty()) {
            curr = stack.pop();
            if (curr.isInteger()) {
                next = curr.getInteger();
                //System.out.println(next);
                return true;
            }
            List<NestedInteger> list = curr.getList();
            for (int i = list.size() - 1; i >= 0; i--) {
                stack.push(list.get(i));
            }
        }
        return false;
    }
}

No comments:

Post a Comment