Skip to content

Commit 467404c

Browse files
refactor 251
1 parent bafccaf commit 467404c

File tree

1 file changed

+21
-45
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+21
-45
lines changed

src/main/java/com/fishercoder/solutions/_251.java

Lines changed: 21 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -5,58 +5,34 @@
55
import java.util.List;
66
import java.util.Queue;
77

8-
/**Implement an iterator to flatten a 2d vector.
9-
10-
For example,
11-
Given 2d vector =
12-
13-
[
14-
[1,2],
15-
[3],
16-
[4,5,6]
17-
]
18-
By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,2,3,4,5,6].
19-
20-
Hint:
21-
22-
How many variables do you need to keep track?
23-
Two variables is all you need. Try with x and y.
24-
Beware of empty rows. It could be the first few rows.
25-
To write correct code, think about the invariant to maintain. What is it?
26-
The invariant is x and y must always point to a valid point in the 2d vector. Should you maintain your invariant ahead of time or right when you need it?
27-
Not sure? Think about how you would implement hasNext(). Which is more complex?
28-
Common logic in two different places should be refactored into a common method.
29-
30-
Follow up:
31-
As an added challenge, try to code it using only iterators in C++ or iterators in Java.*/
32-
338
public class _251 {
349

35-
class Vector2D implements Iterator<Integer> {
36-
private Queue<Integer> cache;
37-
private List<List<Integer>> vec2d;
38-
39-
public Vector2D(List<List<Integer>> vec2d) {
40-
this.vec2d = vec2d;
41-
this.cache = new LinkedList<Integer>();
42-
if (vec2d != null && vec2d.size() > 0) {
43-
for (List<Integer> list : vec2d) {
44-
for (int i : list) {
45-
cache.offer(i);
10+
public static class Solution1 {
11+
class Vector2D implements Iterator<Integer> {
12+
private Queue<Integer> cache;
13+
private List<List<Integer>> vec2d;
14+
15+
public Vector2D(List<List<Integer>> vec2d) {
16+
this.vec2d = vec2d;
17+
this.cache = new LinkedList<Integer>();
18+
if (vec2d != null && vec2d.size() > 0) {
19+
for (List<Integer> list : vec2d) {
20+
for (int i : list) {
21+
cache.offer(i);
22+
}
4623
}
4724
}
4825
}
49-
}
5026

51-
@Override
52-
public Integer next() {
53-
return cache.poll();
54-
}
27+
@Override
28+
public Integer next() {
29+
return cache.poll();
30+
}
5531

56-
@Override
57-
public boolean hasNext() {
58-
return !cache.isEmpty();
32+
@Override
33+
public boolean hasNext() {
34+
return !cache.isEmpty();
35+
}
5936
}
6037
}
61-
6238
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy