forked from javadev/LeetCode-in-Kotlin
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathRouter.kt
102 lines (94 loc) · 2.97 KB
/
Router.kt
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package g3501_3600.s3508_implement_router
// #Medium #Array #Hash_Table #Binary_Search #Design #Ordered_Set #Queue
// #2025_04_09_Time_202_ms_(100.00%)_Space_172.82_MB_(95.24%)
import java.util.LinkedList
import java.util.Queue
import kotlin.math.max
class Router(private val size: Int) {
private var cur = 0
private val q: Queue<IntArray>
private val map: HashMap<Int, ArrayList<IntArray>>
init {
q = LinkedList<IntArray>()
map = HashMap<Int, ArrayList<IntArray>>()
}
fun addPacket(source: Int, destination: Int, timestamp: Int): Boolean {
if (map.containsKey(destination)) {
var found = false
val list: ArrayList<IntArray> = map[destination]!!
for (i in list.indices.reversed()) {
if (list[i][1] < timestamp) {
break
} else if (list[i][0] == source) {
found = true
break
}
}
if (found) {
return false
}
}
if (map.containsKey(destination)) {
val list: ArrayList<IntArray> = map[destination]!!
list.add(intArrayOf(source, timestamp))
cur++
q.offer(intArrayOf(source, destination, timestamp))
} else {
val temp = ArrayList<IntArray>()
temp.add(intArrayOf(source, timestamp))
cur++
map.put(destination, temp)
q.offer(intArrayOf(source, destination, timestamp))
}
if (cur > size) {
forwardPacket()
}
return true
}
fun forwardPacket(): IntArray? {
if (q.isEmpty()) {
return intArrayOf()
}
val temp = q.poll()
val list: ArrayList<IntArray> = map[temp[1]]!!
list.removeAt(0)
if (list.isEmpty()) {
map.remove(temp[1])
}
cur--
return temp
}
fun getCount(destination: Int, startTime: Int, endTime: Int): Int {
return if (map.containsKey(destination)) {
val list: ArrayList<IntArray> = map[destination]!!
var lower = -1
var higher = -1
for (i in list.indices) {
if (list[i][1] >= startTime) {
lower = i
break
}
}
for (i in list.indices.reversed()) {
if (list[i][1] <= endTime) {
higher = i
break
}
}
if (lower == -1 || higher == -1) {
0
} else {
max(0.0, (higher - lower + 1).toDouble()).toInt()
}
} else {
0
}
}
}
/*
* Your Router object will be instantiated and called as such:
* var obj = Router(memoryLimit)
* var param_1 = obj.addPacket(source,destination,timestamp)
* var param_2 = obj.forwardPacket()
* var param_3 = obj.getCount(destination,startTime,endTime)
*/