Wednesday, April 19, 2017

[LintCode] 601 Flatten 2D Vector 解题报告

Description
Implement an iterator to flatten a 2d vector.



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



思路
因为是2D的vector,所以我们只需要2个index去定位数字:
一个定位sub list的位置,一个定位在sub list下具体元素的位置。



Code
public class Vector2D implements Iterator<Integer> {

    private int ListIndex;
    private int ElementIndex;
    private List<List<Integer>> vec;
    public Vector2D(List<List<Integer>> vec2d) {
        // Initialize your data structure here
        ListIndex = 0;
        ElementIndex = 0;
        vec = vec2d;
    }

    @Override
    public Integer next() {
        // Write your code here
        hasNext();
        return vec.get(ListIndex).get(ElementIndex++);
    }

    @Override
    public boolean hasNext() {
        // Write your code here
        while (ListIndex < vec.size()) {
            if (ElementIndex < vec.get(ListIndex).size()) {
                return true;
            }
            else {
                ListIndex++;
                ElementIndex = 0;
            }
        }
        return false;
    }

    @Override
    public void remove() {}
}

/**
 * Your Vector2D object will be instantiated and called as such:
 * Vector2D i = new Vector2D(vec2d);
 * while (i.hasNext()) v[f()] = i.next();
 */