zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    云计算openstack核心组件——neutron网络服务(9)
    云计算openstack核心组件——neutron网络服务(8)
    flexible.js 布局详解
    libflexible源码阅读
    H5适配方案
    微信分享朋友圈示例代码
    微信接口示例代码
    微信JSSDK上传图片,代码为上传单张图
    H5动画开发快车道
    Centos 6.5 安装 Nginx+MySQL+PHP
  • 原文地址:https://www.cnblogs.com/immiao0319/p/13734290.html
Copyright © 2011-2022 走看看