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里面规避这种情况。
**
但是,这个想法,是大错特错的!!
规避溢出的唯一思路,就是从 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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容