-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLeetCode-251-Flatten-2D-Vector.java
63 lines (52 loc) · 1.23 KB
/
LeetCode-251-Flatten-2D-Vector.java
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// 1. Using a Queue
// class Vector2D {
// Queue<Integer> queue = new LinkedList<>();
// public Vector2D(int[][] v) {
// for (int i = 0; i < v.length; i++) {
// for (int n : v[i]) {
// queue.offer(n);
// }
// }
// }
// public int next() {
// return queue.poll();
// }
// public boolean hasNext() {
// return !queue.isEmpty();
// }
// }
// 2.Using Two Pointers
class Vector2D {
int[][] v;
int totalRows;
int currCol;
int currRow;
public Vector2D(int[][] v) {
this.v = v;
totalRows = v.length;
currCol = 0;
currRow = 0;
}
public int next() {
if (hasNext()) {
return v[currRow][currCol++];
}
return -1;
}
public boolean hasNext() {
while(currRow < totalRows) {
if (currCol < v[currRow].length) {
return true;
}
currRow++;
currCol = 0;
}
return false;
}
}
/**
* Your Vector2D object will be instantiated and called as such:
* Vector2D obj = new Vector2D(v);
* int param_1 = obj.next();
* boolean param_2 = obj.hasNext();
*/