[LeetCode] 251. Flatten 2D Vector

Design an iterator to flatten a 2D vector. It should support the next and hasNext operations.

Implement the Vector2D class:

  • Vector2D(int[][] vec) initializes the object with the 2D vector vec.
  • next() returns the next element from the 2D vector and moves the pointer one step forward. You may assume that all the calls to next are valid.
  • hasNext() returns true if there are still some elements in the vector, and false otherwise.

Example 1:

Input
["Vector2D", "next", "next", "next", "hasNext", "hasNext", "next", "hasNext"]
[[[[1, 2], [3], [4]]], [], [], [], [], [], [], []]
Output
[null, 1, 2, 3, true, true, 4, false]

Explanation
Vector2D vector2D = new Vector2D([[1, 2], [3], [4]]);
vector2D.next();    // return 1
vector2D.next();    // return 2
vector2D.next();    // return 3
vector2D.hasNext(); // return True
vector2D.hasNext(); // return True
vector2D.next();    // return 4
vector2D.hasNext(); // return False

Constraints:

  • 0 <= vec.length <= 200
  • 0 <= vec[i].length <= 500
  • -500 <= vec[i][j] <= 500
  • At most 105 calls will be made to next and hasNext.

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

展开二维向量。

这也是一道考察 iterator 的题目,只不过是把 iterate 的对象变成了一个二维数组。比较偷懒的办法就是先把所有元素放入一个队列,然后遍历队列即可。

Java实现

 1 class Vector2D {
 2     private Queue<Integer> queue = new LinkedList<>();
 3 
 4     public Vector2D(int[][] v) {
 5         for (int i = 0; i < v.length; i++) {
 6             for (int j = 0; j < v[i].length; j++) {
 7                 queue.offer(v[i][j]);
 8             }
 9         }
10     }
11 
12     public int next() {
13         return queue.poll();
14     }
15 
16     public boolean hasNext() {
17         return !queue.isEmpty();
18     }
19 }
20 
21 /**
22  * Your Vector2D object will be instantiated and called as such:
23  * Vector2D obj = new Vector2D(v);
24  * int param_1 = obj.next();
25  * boolean param_2 = obj.hasNext();
26  */

 

不使用队列也能做,无非考察的是你对遍历二维矩阵的坐标的敏感程度。注意这道题给的二维向量,每一行的元素个数并不一样,所以不能用类似遍历二维矩阵那样的方式去遍历。

Java实现

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

 

LeetCode 题目总结

posted @ 2020-08-27 02:09  CNoodle  阅读(199)  评论(0编辑  收藏  举报