zoukankan      html  css  js  c++  java
  • 251. Flatten 2D Vector 平铺矩阵

    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:

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

    Example 2:

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


    思路:for each的循环!判断i是不是integer,如果不是,就继续flatten它

    注意要初始化

    flattenedList = new LinkedList<Integer>();
    public class NestedIterator implements Iterator<Integer> {
        LinkedList<Integer> flattenedList;
        Iterator<Integer> iterator;
    
        public NestedIterator(List<NestedInteger> nestedList) {
            //注意要初始化
            flattenedList = new LinkedList<Integer>();
            flatten(nestedList);
            iterator = flattenedList.iterator();
        }
        
        public void flatten(List<NestedInteger> nestedList) {
            for (NestedInteger ni : nestedList) {
                if (ni.isInteger()) {
                    flattenedList.add(ni.getInteger());
                }else {
                    flatten(ni.getList());
                }
            }
        }
    
        @Override
        public Integer next() {
            return iterator.next();
        }
    
        @Override
        public boolean hasNext() {
            return iterator.hasNext();
        }
    }
    
    /**
     * Your NestedIterator object will be instantiated and called as such:
     * NestedIterator i = new NestedIterator(nestedList);
     * while (i.hasNext()) v[f()] = i.next();
     */
    View Code


  • 相关阅读:
    POJ 3252 Round Numbers
    HDU 1024 Max Sum Plus
    HDU 1024 Max Sum Plus Plus
    HDU 1698 Just a Hook
    HDU 1049 Climbing Worm
    HDU 3386 Reversi
    树状数组总结
    HDU 1556 Color the ball
    树形数组
    HDU 1188 敌兵布阵
  • 原文地址:https://www.cnblogs.com/immiao0319/p/13875878.html
Copyright © 2011-2022 走看看