-
Notifications
You must be signed in to change notification settings - Fork 126
/
Copy pathjdalma.kt
59 lines (53 loc) Β· 1.73 KB
/
jdalma.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
package leetcode_study
import io.kotest.matchers.shouldBe
import org.junit.jupiter.api.Test
import kotlin.math.max
import kotlin.math.min
class `insert-interval` {
/**
* TC: O(n), SC: O(n)
*/
fun insert(intervals: Array<IntArray>, newInterval: IntArray): Array<IntArray> {
if (intervals.isEmpty()) return arrayOf(newInterval)
return justIterate(intervals, newInterval)
}
private fun justIterate(intervals: Array<IntArray>, newInterval: IntArray): Array<IntArray> {
val result = mutableListOf<IntArray>()
var new: IntArray? = newInterval
for (interval in intervals) {
if (new != null) {
if (new[1] < interval[0]) {
// new λ²μκ° λ μμ μλ€
result.add(new)
result.add(interval)
new = null
} else if (new[0] > interval[1]) {
// new λ²μκ° λ λ€μ μμ΄ λ€λ₯Έ λ²μμ ν¬ν¨λ κ°λ₯μ±μ΄ μμ
result.add(interval)
} else {
new[0] = min(new[0], interval[0])
new[1] = max(new[1], interval[1])
}
} else {
result.add(interval)
}
}
if (new != null) {
result.add(new)
}
return result.toTypedArray()
}
@Test
fun name() {
insert(
arrayOf(
intArrayOf(1,2),
intArrayOf(3,5),
intArrayOf(6,7),
intArrayOf(8,10),
intArrayOf(12,16)
),
intArrayOf(4,8)
) shouldBe arrayOf(intArrayOf(1,2), intArrayOf(3,10), intArrayOf(12,16))
}
}