https://leetcode.com/problems/flatten-2d-vector/description/
题目很简单,两个思路:
- 双 index
- 双 iterator
public class Vector2D implements Iterator<Integer> {
private Iterator<List<Integer>> listsIter;
private Iterator<Integer> listIter;
public Vector2D(List<List<Integer>> vec2d) {
listsIter = vec2d.iterator();
if (listsIter.hasNext()) {
listIter = listsIter.next().iterator();
}
}
@Override
public Integer next() {
// hasNext() should always be called before next(), so these few lines are not neccessary.
// while (!listIter.hasNext()) {
// listIter = listsIter.next().iterator();
// }
return listIter.next();
}
@Override
public boolean hasNext() {
if (listIter == null) {
return false;
}
while (listsIter.hasNext() && !listIter.hasNext()) {
listIter = listsIter.next().iterator();
}
return listIter.hasNext();
}
}
Solution from: https://www.youtube.com/watch?v=Hwk1CD86YmA&list=PLvyIyKZVcfAn_9zI9qcHTtNbhLz6OFd_c&index=3
List get 复杂度取决于 Class。ArrayList O(1), LinkedList O(n)
网友评论