LeetCode 341. Flatten Nested List Iterator

原题链接在这里:https://leetcode.com/problems/flatten-nested-list-iterator/

题目:

Given a nested list of integers, implement an iterator to flatten it.

Each element is either an integer, or a list -- whose elements may also be integers or other lists.

Example 1:
Given the list [[1,1],2,[1,1]],

By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1].

Example 2:
Given the list [1,[4,[6]]],

By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6].

题解:

Stack<NestedInteger> stk 从后向前存储nestedList的每个item. hasNext() 拿出stk顶部item, 若不是Integer就把该item从后向前放回stk中.

Note: [[]], in case of this, need to make sure the first is an integer.

Time Complexity: next, O(1). hasNext, O(n).

Space: O(n).

AC Java:

 1 /**
 2  * // This is the interface that allows for creating nested lists.
 3  * // You should not implement it, or speculate about its implementation
 4  * public interface NestedInteger {
 5  *
 6  *     // @return true if this NestedInteger holds a single integer, rather than a nested list.
 7  *     public boolean isInteger();
 8  *
 9  *     // @return the single integer that this NestedInteger holds, if it holds a single integer
10  *     // Return null if this NestedInteger holds a nested list
11  *     public Integer getInteger();
12  *
13  *     // @return the nested list that this NestedInteger holds, if it holds a nested list
14  *     // Return empty list if this NestedInteger holds a single integer
15  *     public List<NestedInteger> getList();
16  * }
17  */
18 public class NestedIterator implements Iterator<Integer> {
19     Stack<NestedInteger> stk;
20     public NestedIterator(List<NestedInteger> nestedList) {
21         stk = new Stack<>();
22         putListOntoStk(nestedList);
23     }
24 
25     @Override
26     public Integer next() {
27         if(!hasNext()){
28             return null;
29         }
30 
31         return stk.pop().getInteger();
32     }
33 
34     @Override
35     public boolean hasNext() {
36         while(!stk.isEmpty() && !stk.peek().isInteger()){
37             List<NestedInteger> cur = stk.pop().getList();
38             putListOntoStk(cur);
39         }
40 
41         return !stk.isEmpty();
42     }
43 
44     private void putListOntoStk(List<NestedInteger> nestedList){
45         for(int i = nestedList.size() - 1; i >= 0; i--){
46             stk.push(nestedList.get(i));
47         }
48     }
49 }
50 
51 /**
52  * Your NestedIterator object will be instantiated and called as such:
53  * NestedIterator i = new NestedIterator(nestedList);
54  * while (i.hasNext()) v[f()] = i.next();
55  */

类似Nested List Weight SumZigzag IteratorMini ParserFlatten 2D Vector.

posted @ 2017-02-25 03:46  Dylan_Java_NYC  阅读(720)  评论(0编辑  收藏  举报