-
Notifications
You must be signed in to change notification settings - Fork 887
/
Vector2D.swift
49 lines (41 loc) · 1.04 KB
/
Vector2D.swift
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
/**
* Question Link: https://leetcode.com/problems/flatten-2d-vector/
* Primary idea: Two pointers, one to iterate arrays,
* one to interate elements in a specifc array
*
* Time Complexity: O(n) for next, O(n) for hasNext()
* Space Complexity: O(n)
*
*/
class Vector2D {
var arrayIdx: Int
var elementIdx: Int
var arrays: [[Int]]
init(_ v: [[Int]]) {
arrays = v
arrayIdx = 0
elementIdx = 0
}
func next() -> Int {
if hasNext() {
let element = arrays[arrayIdx][elementIdx]
elementIdx += 1
return element
}
fatalError("Invalid next call")
}
func hasNext() -> Bool {
findNext()
return arrayIdx < arrays.count
}
private func findNext() {
while arrayIdx < arrays.count {
if elementIdx < arrays[arrayIdx].count {
return
} else {
arrayIdx += 1
elementIdx = 0
}
}
}
}