美文网首页
251. Flatten 2D Vector

251. Flatten 2D Vector

作者: Super_Alan | 来源:发表于2018-04-19 07:27 被阅读0次

https://leetcode.com/problems/flatten-2d-vector/description/

题目很简单,两个思路:

  • 双 index
  • 双 iterator
public class Vector2D implements Iterator<Integer> {
    private Iterator<List<Integer>> listsIter;
    private Iterator<Integer> listIter;
    
    public Vector2D(List<List<Integer>> vec2d) {
        listsIter = vec2d.iterator();
        if (listsIter.hasNext()) {
            listIter = listsIter.next().iterator();
        }
    }

    @Override
    public Integer next() {
        // hasNext() should always be called before next(), so these few lines are not neccessary.
        // while (!listIter.hasNext()) {
        //     listIter = listsIter.next().iterator();
        // }
        
        return listIter.next();
    }

    @Override
    public boolean hasNext() {
        if (listIter == null) {
            return false;
        }
        
        while (listsIter.hasNext() && !listIter.hasNext()) {
            listIter = listsIter.next().iterator();
        }
        
        return listIter.hasNext();
    }
}

Solution from: https://www.youtube.com/watch?v=Hwk1CD86YmA&list=PLvyIyKZVcfAn_9zI9qcHTtNbhLz6OFd_c&index=3

双 index.png

List get 复杂度取决于 Class。ArrayList O(1), LinkedList O(n)

相关文章

网友评论

      本文标题:251. Flatten 2D Vector

      本文链接:https://www.haomeiwen.com/subject/etyikftx.html