-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy path251. Flatten 2D Vector.c
87 lines (68 loc) · 1.81 KB
/
251. Flatten 2D Vector.c
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/*
251. Flatten 2D Vector
Implement an iterator to flatten a 2d vector.
For example,
Given 2d vector =
[
[1,2],
[3],
[4,5,6]
]
By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,2,3,4,5,6].
Follow up:
As an added challenge, try to code it using only iterators in C++ or iterators in Java.
*/
struct Vector2D {
int rowsz;
int *colsz;
int **vec;
int r;
int c;
};
struct Vector2D *vector2DCreate(int** vec2d, int vec2dRowSize, int* vec2dColSizes) {
struct Vector2D *iter = malloc(sizeof(struct Vector2D));
//assert(iter);
iter->rowsz = vec2dRowSize;
iter->colsz = vec2dColSizes;
iter->vec = vec2d;
iter->r = iter->c = 0;
return iter;
}
bool vector2DHasNext(struct Vector2D *iter) {
while (iter->r < iter->rowsz) {
if (iter->c < iter->colsz[iter->r]) return true;
iter->r ++;
iter->c = 0;
}
return false;
}
int vector2DNext(struct Vector2D *iter) {
return iter->vec[iter->r][iter->c ++];
}
/** Deallocates memory previously allocated for the iterator */
void vector2DFree(struct Vector2D *iter) {
free(iter);
}
/**
* Your Vector2D will be called like this:
* struct Vector2D *i = vector2DCreate(vec2d, rowSize, colSizes);
* while (vector2DHasNext(i)) printf("%d\n", vector2DNext(i));
* vector2DFree(i);
*/
/*
Difficulty:Medium
Total Accepted:26.6K
Total Submissions:66K
Companies Google Airbnb Twitter Zenefits
Related Topics Design
Similar Questions
Binary Search Tree Iterator
Zigzag Iterator
Peeking Iterator
Flatten Nested List Iterator
*/