Leetcode - 251. 展开二维向量

代码未经过验证,但解题思路是正确的:
class Vector2D{

    /**
     * 题目要求:实现一个Vector2D类,它能完成对List<List<Integer>>集合的遍历
     * 举例说明:使用Vector2D来遍历[[1, 2], [3], [4, 5, 6]]集合,最终结果是[1, 2, 3, 4, 5, 6]
     */
    
    //bigIter用于遍历整个List<List<Integer>>集合
    private Iterator<List<Integer>> bigIter;

    //smallIter用于遍历某个List<Integer>集合
    private Iterator<Integer> smallIter;

    public Vector2D(List<List<Integer>> vec2d){
        
        //为避免麻烦,我直接假设vec2d不为null且至少有一个List<Integer>元素
        if(vec2d == null || vec2d.isEmpty())
            throw new RuntimeException("Empty list is not allowed!");
        
        bigIter = vec2d.iterator();

        //先用smallIter来遍历第一个List<Integer>集合
        smallIter = bigIter.next().iterator();
    }
    
    public boolean hasNext(){

        //如果当前的List<Integer>已经遍历完成,则获取下一个List<Integer>的迭代器
        while(bigIter.hasNext() && !smallIter.hasNext())
            smallIter = bigIter.next().iterator();
        
        return smallIter.hasNext();
    }
    
    public int next(){

        //如果当前的List<Integer>已经遍历完成,则获取下一个List<Integer>的迭代器
        while(bigIter.hasNext() && !smallIter.hasNext())
            smallIter = bigIter.next().iterator();
        
        return smallIter.next();
    }
}
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务