Skip to content

Commit ceb10b8

Browse files
committed
Refactored Flatten 2D Vector.java
1 parent 5b428bd commit ceb10b8

File tree

1 file changed

+26
-37
lines changed

1 file changed

+26
-37
lines changed

Medium/Flatten 2D Vector.java

Lines changed: 26 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,44 +1,33 @@
1-
class Vector2D implements Iterator<Integer> {
1+
class Vector2D {
2+
int vectorIdx;
3+
int currIdx;
4+
int[][] v;
5+
public Vector2D(int[][] v) {
6+
vectorIdx = 0;
7+
currIdx = 0;
8+
this.v = v;
9+
}
210

3-
Iterator<List<Integer>> listIterator;
4-
Iterator<Integer> iterator;
5-
boolean flag;
11+
public int next() {
12+
hasNext();
13+
return v[vectorIdx][currIdx++];
14+
}
615

7-
public Vector2D(List<List<Integer>> vec2d) {
8-
listIterator = vec2d.iterator();
9-
check();
10-
}
11-
12-
private void check() {
13-
while (listIterator.hasNext()) {
14-
List<Integer> list = listIterator.next();
15-
if (list.size() > 0) {
16-
iterator = list.iterator();
17-
break;
18-
}
19-
}
20-
21-
flag = iterator != null;
22-
}
23-
24-
@Override
25-
public Integer next() {
26-
int num = iterator.next();
27-
if (!iterator.hasNext()) {
28-
iterator = null;
29-
check();
30-
}
31-
32-
return num;
33-
}
34-
35-
@Override
36-
public boolean hasNext() {
37-
return flag;
16+
public boolean hasNext() {
17+
while (vectorIdx < v.length) {
18+
if (currIdx < v[vectorIdx].length) {
19+
return true;
20+
}
21+
vectorIdx++;
22+
currIdx = 0;
3823
}
24+
return false;
25+
}
3926
}
27+
4028
/**
4129
* Your Vector2D object will be instantiated and called as such:
42-
* Vector2D i = new Vector2D(vec2d);
43-
* while (i.hasNext()) v[f()] = i.next();
30+
* Vector2D obj = new Vector2D(v);
31+
* int param_1 = obj.next();
32+
* boolean param_2 = obj.hasNext();
4433
*/

0 commit comments

Comments
 (0)