|
| 1 | +// Time complexity O(nlogn) and space complexity O(n) |
| 2 | +// Find solution with optimized space complexity below |
| 3 | +classSolution { |
| 4 | +funremoveCoveredIntervals(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 | +classSolution { |
| 23 | +funremoveCoveredIntervals(intervals:Array<IntArray>):Int { |
| 24 | + intervals.sortWith(compareBy({ it[0] }, {-it[1] })) |
| 25 | + |
| 26 | +var prev= intervals[0] |
| 27 | +var res=1 |
| 28 | +for (intervalin 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 | +} |