Leetcode - Flatten 2D Vector

Screenshot from 2016-02-17 22:18:41.png

My code:

public class Vector2D {
    private int lineNum = 0;
    private int index = 0;
    private List<List<Integer>> l;
    int k = 0;
    public Vector2D(List<List<Integer>> vec2d) {
        l = vec2d;
        k = vec2d.size();
    }

    public int next() {
        int ret = l.get(lineNum).get(index);
        index++;
        if (index >= l.get(lineNum).size()) {
            index = 0;
            lineNum++;
        }
        return ret;
    }

    public boolean hasNext() {
        while (lineNum < k) {
            if (l.get(lineNum).size() != 0)
                return true;
            lineNum++;
        }
        return false;
    }
}

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

這道題目不是很難。但是一個corner case 一直卡住,也沒能想出為什么。直到用了eclipse debug之后才知道。
如果 list 里面有空的list,但是他又算一行,所以 hasNext() 無法檢測出來。
這個時候,index = 0,從他里面取出元素的話,會發生溢出。
然后我就想著從next里面規避這種情況。
**
但是,這個想法,是大錯特錯的?。?br> 規避溢出的唯一思路,就是從 hasNext() 入手。next() 永遠不需要考慮是否會溢出。直接取。
hasNext() 負責判斷溢出!
**

Anyway, Good luck, RIchardo!

My code:

public class Vector2D implements Iterator<Integer> {
    List<Iterator<Integer>> list = new ArrayList<Iterator<Integer>>();
    int counter = 0;
    int total = 0;
    public Vector2D(List<List<Integer>> vec2d) {
        for (List<Integer> temp : vec2d) {
            list.add(temp.iterator());
        }
        total = vec2d.size();
    }

    @Override
    public Integer next() {
        return list.get(counter).next();
    }

    @Override
    public boolean hasNext() {
        while (counter < total) {
            if (list.get(counter).hasNext()) {
                return true;
            }
            else {
                counter++;
            }
        }
        return false;
    }
}

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

這些還是可以用, List<Iterator> 的思路來做。
不難。

Anyway, Good luck, Richardo! -- 09/14/2016

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容