LeetCode Flatten 2D Vector

原题链接在这里:https://leetcode.com/problems/flatten-2d-vector/

题目:

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].

题解:

用两个index 分别记录list 的 index 和当前 list的element index.

Time Complexity: Vector2D() O(1). hasNext() O(1). next(1). Space: O(1).

AC Java:

 1 public class Vector2D {
 2     List<List<Integer>> listOfList;
 3     int listIndex;
 4     int elemIndex;
 5     public Vector2D(List<List<Integer>> vec2d) {
 6         listOfList = vec2d;
 7         listIndex = 0;
 8         elemIndex = 0;
 9     }
10 
11     public int next() {
12         return listOfList.get(listIndex).get(elemIndex++);
13     }
14 
15     public boolean hasNext() {
16         while(listIndex < listOfList.size()){
17             if(elemIndex < listOfList.get(listIndex).size()){
18                 return true;
19             }else{
20                 listIndex++;
21                 elemIndex = 0;
22             }
23         }
24         return false;
25     }
26 }
27 
28 /**
29  * Your Vector2D object will be instantiated and called as such:
30  * Vector2D i = new Vector2D(vec2d);
31  * while (i.hasNext()) v[f()] = i.next();
32  */

 

你可能感兴趣的:(LeetCode Flatten 2D Vector)