-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy path0251-flatten-2d-vector.js
More file actions
44 lines (41 loc) · 1.14 KB
/
0251-flatten-2d-vector.js
File metadata and controls
44 lines (41 loc) · 1.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/**
* 251. Flatten 2D Vector
* https://leetcode.com/problems/flatten-2d-vector/
* Difficulty: Medium
*
* 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.
*/
/**
* @param {number[][]} vec
*/
var Vector2D = function(vec) {
this.vector = vec;
this.row = 0;
this.col = 0;
};
/**
* @return {number}
*/
Vector2D.prototype.next = function() {
while (this.row < this.vector.length && this.col >= this.vector[this.row].length) {
this.row++;
this.col = 0;
}
return this.vector[this.row][this.col++];
};
/**
* @return {boolean}
*/
Vector2D.prototype.hasNext = function() {
while (this.row < this.vector.length && this.col >= this.vector[this.row].length) {
this.row++;
this.col = 0;
}
return this.row < this.vector.length;
};