-
[LeetCode / Kotlin] Remove Covered IntervalsETC 2024. 7. 12. 16:35반응형
문제
Given an array intervals where intervals[i] = [li, ri] represent the interval [li, ri), remove all intervals that are covered by another interval in the list.
The interval [a, b) is covered by the interval [c, d) if and only if c <= a and b <= d.
Return the number of remaining intervals.Example 1:
Input: intervals = [[1,4],[3,6],[2,8]] Output: 2 Explanation: Interval [3,6] is covered by [2,8], therefore it is removed.
Example 2:
Input: intervals = [[1,4],[2,3]] Output: 1
Constraints:
- 1 <= intervals.length <= 1000
- intervals[i].length == 2
- 0 <= li < ri <= 105
나의 풀이
class Solution { fun removeCoveredIntervals(intervals: Array<IntArray>): Int { // 포함하냐? -> start가 이하, end가 이상. // 그럼 비교는 어떻게? -> 큰 범위 순(start는 오름, end는 내림)으로 정렬 후, end가 갱신되지않으면 포함된것, end가 갱신되면 새로운 범위 val sortedIntervals = intervals.sortedWith( compareBy({ it[0] }, { -it[1] }) ) var ans = 0 var pEnd = 0 for (i in sortedIntervals) { if (pEnd < i[1]) { pEnd = i[1] ans++ } } return ans } }
반응형'ETC' 카테고리의 다른 글
[LeetCode / Kotlin] Merge Intervals (0) 2024.07.12 [LeetCode / Kotlin] Add Binary (0) 2024.07.12 [LeetCode / Kotlin] Pascal's Triangle (0) 2024.07.11 [LeetCode / Kotlin] Spiral Matrix (0) 2024.07.11 [LeetCode / Kotlin] Search Insert Position (0) 2024.07.11