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

    Design and implement an iterator to flatten a 2d vector. It should support the following operations: next and hasNext.

     

    Example:

    Vector2D iterator = new Vector2D([[1,2],[3],[4]]);
    
    iterator.next(); // return 1
    iterator.next(); // return 2
    iterator.next(); // return 3
    iterator.hasNext(); // return true
    iterator.hasNext(); // return true
    iterator.next(); // return 4
    iterator.hasNext(); // return false

    思路:

    两者之中有一个存在next()就行了
    这个思路不对,只能从colIter中取next。所以应该是next()中只有一个功能:返回col_itr.next()

    如果一开始就用while循环,1,2,3,4 调用next直接返回最后一个了
    所以一开始要用if 先存一行 保证next()直接调用是有东西的

    这个代码signature不一样,无法通过,但是思路是对的:

    public class Vector2D implements Iterator<Integer> {
        private Iterator<List<Integer>> row_itr; //row iterator
        private Iterator<Integer> col_itr;       //col iterator
    
        public Vector2D(List<List<Integer>> vec2d) {
            row_itr = vec2d.iterator();
            //if row_itr doesn't have next, it means vec2d is empty
            //in this case, col_itr won't get initialized
            if(row_itr.hasNext())
                col_itr = row_itr.next().iterator();
        }
    
        @Override
        public Integer next() {
            //we won't call next() unless we are sure that hasNext() is true, meaning col_itr.hasNext() is true
            return col_itr.next();
        }
    
        @Override
        public boolean hasNext() {
            //check whether vec2d is empty
            if(col_itr==null) return false;
            
            //important!!! we do update here in hasNext()
            //update col_itr and row_itr until col_itr.hasNext() or row_itr.hasNext() is false
            while(!col_itr.hasNext()&&row_itr.hasNext())
                col_itr = row_itr.next().iterator();
            
            return col_itr.hasNext();      
        }
    }
    View Code
     
  • 相关阅读:
    Java并发--线程间协作的两种方式:wait、notify、notifyAll和Condition
    Java并发--Java线程面试题 Top 50
    Java并发--Timer和TimerTask
    Spring配置--Aop配置详情
    Spring配置--tx事务配置方式
    java并发--Callable、Future和FutureTask
    java并发--CountDownLatch、CyclicBarrier和Semaphore
    精通Matlab数字图像处理与识别
    油砂资源状况与储量评估方法
    家庭自制药蛋
  • 原文地址:https://www.cnblogs.com/immiao0319/p/13733281.html
Copyright © 2011-2022 走看看