forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
1288-remove-covered-intervals.kt
38 lines (30 loc) · 1.03 KB
/
1288-remove-covered-intervals.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
// Time complexity O(nlogn) and space complexity O(n)
// Find solution with optimized space complexity below
class Solution {
fun removeCoveredIntervals(intervals: Array<IntArray>): Int {
intervals.sortWith(compareBy({ it[0] }, { -it[1] }))
val res = LinkedList<IntArray>().apply { add(intervals[0]) }
for ((l, r) in intervals) {
val (prevL, prevR) = res.peekLast()
if (prevL <= l && prevR >= r)
continue
res.addLast(intArrayOf(l, r))
}
return res.size
}
}
// Time complexity O(nlogn) and space complexity O(1)
class Solution {
fun removeCoveredIntervals(intervals: Array<IntArray>): Int {
intervals.sortWith(compareBy({ it[0] }, { -it[1] }))
var prev = intervals[0]
var res = 1
for (interval in intervals) {
if (prev[0] <= interval[0] && prev[1] >= interval[1])
continue
prev = interval
res++
}
return res
}
}