File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change 1+ // Time complexity O(nlogn) and space complexity O(n)
2+ // Find solution with optimized space complexity below
3+ class Solution {
4+ fun removeCoveredIntervals (intervals : Array <IntArray >): Int {
5+ intervals.sortWith(compareBy({ it[0 ] }, { - it[1 ] }))
6+
7+ val res = LinkedList <IntArray >().apply { add(intervals[0 ]) }
8+ for ((l, r) in intervals) {
9+ val (prevL, prevR) = res.peekLast()
10+
11+ if (prevL <= l && prevR >= r)
12+ continue
13+
14+ res.addLast(intArrayOf(l, r))
15+ }
16+
17+ return res.size
18+ }
19+ }
20+
21+ // Time complexity O(nlogn) and space complexity O(1)
22+ class Solution {
23+ fun removeCoveredIntervals (intervals : Array <IntArray >): Int {
24+ intervals.sortWith(compareBy({ it[0 ] }, { - it[1 ] }))
25+
26+ var prev = intervals[0 ]
27+ var res = 1
28+ for (interval in intervals) {
29+ if (prev[0 ] <= interval[0 ] && prev[1 ] >= interval[1 ])
30+ continue
31+
32+ prev = interval
33+ res++
34+ }
35+
36+ return res
37+ }
38+ }
You can’t perform that action at this time.
0 commit comments