LeetCode 251. Flatten 2D Vector

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

题目:

Implement an iterator to flatten a 2d vector.

Example:

Input: 2d vector =
[
  [1,2],
  [3],
  [4,5,6]
]
Output: [1,2,3,4,5,6]
Explanation: By calling next repeatedly until hasNext returns false, 
             the order of elements returned by next should be: [1,2,3,4,5,6].

Follow up:
As an added challenge, try to code it using only iterators in C++ or iterators in Java.

题解:

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

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

AC Java:

 1 class Vector2D {
 2     int [][] vec;
 3     int i;
 4     int j;
 5 
 6     public Vector2D(int[][] vec) {
 7         this.vec = vec;
 8         i = 0;
 9         j = 0;
10     }
11     
12     public int next() {
13         if(hasNext()){
14             return vec[i][j++];
15         }else{
16             return -1;
17         }
18     }
19     
20     public boolean hasNext() {
21         while(i < vec.length){
22             if(j < vec[i].length){
23                 return true;
24             }else{
25                 i++;
26                 j = 0;
27             }
28         }
29 
30         return false;
31     }
32 }
33 
34 /**
35  * Your Vector2D object will be instantiated and called as such:
36  * Vector2D obj = new Vector2D(vec);
37  * int param_1 = obj.next();
38  * boolean param_2 = obj.hasNext();
39  */

Follow up 要用Iterator class.

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

AC Java:

 1 public class Vector2D implements Iterator<Integer> {
 2     Iterator<List<Integer>> i;
 3     Iterator<Integer> j;
 4     
 5     public Vector2D(List<List<Integer>> vec2d) {
 6         i = vec2d.iterator();        
 7     }
 8 
 9     @Override
10     public Integer next() {
11         return j.next();
12     }
13 
14     @Override
15     public boolean hasNext() {
16         while((j==null || !j.hasNext()) && i.hasNext()){
17             j = i.next().iterator();
18         }
19         
20         return j!=null && j.hasNext();
21     }
22 }
23 
24 /**
25  * Your Vector2D object will be instantiated and called as such:
26  * Vector2D i = new Vector2D(vec2d);
27  * while (i.hasNext()) v[f()] = i.next();
28  */

类似Flatten Nested List Iterator.

posted @ 2016-02-25 11:48  Dylan_Java_NYC  阅读(645)  评论(0编辑  收藏  举报