Flatten 2D Vector

LintCode Q 607 - Flatten 2D Vector

Implement an iterator to flatten a 2d vector.

Example 1: Input:[[1,2],[3],[4,5,6]] ; Output:[1,2,3,4,5,6]

Example 2: Input:[[7,9],[5]] ; Output:[7,9,5]

Solution

Code:

public class Vector2D implements Iterator<Integer> {

	private List<Iterator<Integer>> iters;
	private int pointer;
	
	public Vector2D(List<List<Integer>> vec2d) {
		// Initialize your data structure here
		iters = new ArrayList<>();
		for (List<Integer> list: vec2d) {
			if (list.size() > 0)
				iters.add(list.iterator());
		}

		pointer = 0;
	}

	@Override
	public Integer next() {
		// Write your code here
		int curr = iters.get(pointer).next();

		if (!iters.get(pointer).hasNext())
			pointer++;

		return curr;
	}

	@Override
	public boolean hasNext() {
		// Write your code here
		return pointer < iters.size();
	}

	@Override
	public void remove() {}
}

   Reprint policy


《Flatten 2D Vector》 by Tong Shi is licensed under a Creative Commons Attribution 4.0 International License
  TOC