• 341. 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:

    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].

    不是展开么,不知道为啥要用next() hasNext()
    //这两个函数可能确实没啥用,只是调用一下罢了。

    如果是个list,就要add list吗?也不对啊。需要再加一个recursion的函数,让它自己递归

    里面用for each循环

    iterator不需要初始化

    public class NestedIterator implements Iterator<Integer> {
        Iterator<Integer> iterator;
        List<Integer> flattenedList = new ArrayList();
    
        public NestedIterator(List<NestedInteger> nestedList) {
            flatten(nestedList);
            iterator = flattenedList.iterator();
        }
        
        public void flatten(List<NestedInteger> nestedList) {
            for (NestedInteger i : nestedList) {
                if (i.isInteger()) {
                    flattenedList.add(i.getInteger());
                }else {
                    flatten(i.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
  • 相关阅读:
    The Single Responsibility Principle
    MSComDlg.CommonDialogserver不能创建对象错误的解决
    Hadoop的HA机制(Zookeeper集群+Hadoop集群)配置记录
    linux怎样查看port被谁占用
    hadoop配置说明
    C#中的继承与多态还有接口
    MySQL DATE_FORMAT() 函数
    MySQL处理数据库和表的常用命令
    mysql 增加用户
    sql2008连接数据库问题
  • 原文地址:https://www.cnblogs.com/immiao0319/p/13734290.html
Copyright © 2020-2023  润新知