Implement an iterator to flatten a 2d vector. For 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].
I think the hint provided by Leetcode is good:
Hint:
x
and y
. x
and y
must always point to a valid point in the 2d vector. Should you maintain your invariant ahead of time or right when you need it?hasNext()
. Which is more complex?So we maintain a set of (x, y), where they point to a valid none empty point in this 2d vector, and this point is also the next element that is going to return. When initializing, set (x, y) to be the first position of a none empty valid point. Every time after calling Next() function, set it to be the next valid position. y++ or y=0 when switch rows. Continue the process until x reaches vec.size()
1 public class Vector2D { 2 List<List<Integer>> vec; 3 int len; 4 int x; 5 int y; 6 7 public Vector2D(List<List<Integer>> vec2d) { 8 this.vec = vec2d; 9 this.len = vec.size(); 10 int i = 0; 11 while (i<len && vec.get(i).size() == 0) { 12 i++; 13 } 14 this.x = i; 15 this.y = 0; 16 } 17 18 public int next() { 19 int result = Integer.MAX_VALUE; 20 if (hasNext()) { 21 result = vec.get(x).get(y); 22 if (y < vec.get(x).size()-1) y++; 23 else { 24 x++; 25 while (x<vec.size() && vec.get(x).size()==0) { 26 x++; 27 } 28 y = 0; 29 } 30 } 31 return result; 32 } 33 34 public boolean hasNext() { 35 return (x<len)? true : false; 36 } 37 } 38 39 /** 40 * Your Vector2D object will be instantiated and called as such: 41 * Vector2D i = new Vector2D(vec2d); 42 * while (i.hasNext()) v[f()] = i.next(); 43 */
原文:http://www.cnblogs.com/EdwardLiu/p/5065501.html