Flatten 2D Vector

题目地址:
https://leetcode.com/problems/flatten-2d-vector/#/description

题目:
Implement an iterator to flatten a 2d vector.
For example,
Given 2d vector =
[
  [1,2],
  [3],
  [4,5,6]
]
By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,2,3,4,5,6].
/**
 * Your Vector2D object will be instantiated and called as such:
 * Vector2D i = new Vector2D(vec2d);
 * while (i.hasNext()) v[f()] = i.next();
 */
Follow up:
As an added challenge, try to code it using only iterators in C++ or iterators in Java.

解题思路:
这是一道设计题,首先要明白的是要存每个1D array,这里可以使用的数据结构是queue。因为在call next() 之前都会判断hasNext(), 所以当curr是空的时候,在hasNext() 的时候就要更新。

代码:


private Queue<Iterator<Integer>> queue = new LinkedList<Iterator<Integer>>();
private Iterator<Integer> current = null;
public Vector2D(List<List<Integer>> vec2d) {
    for(int i = 0; i < vec2d.size(); i++){
        queue.add(vec2d.get(i).iterator());
    }
    current = queue.poll();
}
@Overridepublic Integer next() {
    if(!current.hasNext()){
        return -1;
    }
    return current.next();
}
@Overridepublic boolean hasNext() {
    if(current == null){
        return false;
    }
    while(!current.hasNext()){
        if(!queue.isEmpty()){
            current = queue.poll();
        }
        else{
            return false;
        }
    }
    return true;
}




Comments

Popular Posts