-
[LeetCode / Kotlin] Merge IntervalsETC 2024. 7. 12. 16:31반응형
문제
Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.
Example 1:
Input: intervals = [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]] Explanation: Since intervals [1,3] and [2,6] overlap, merge them into [1,6].
Example 2:
Input: intervals = [[1,4],[4,5]] Output: [[1,5]] Explanation: Intervals [1,4] and [4,5] are considered overlapping.
Constraints:
- - 1 <= intervals.length <= 104
- intervals[i].length == 2
- 0 <= starti <= endi <= 104
나의 풀이
class Solution { fun merge(intervals: Array<IntArray>): Array<IntArray> { // 겹치는 범위가 있으면 통합시켜라 // 겹친다 -> start와 end에 대한 비교 // 비교는 어떻게? -> end 오름차순으로 정렬 후, 반복문을 돈다. 이때, 겹치면 커서end값 갱신, 아니면 커서 start, 커서 end 갱신 val sortedIntervals = intervals.sortedBy { it[0] } val ans = mutableListOf<IntArray>() var (cursorS, cursorE) = sortedIntervals.first() for (i in 1 until sortedIntervals.size) { val (start, end) = sortedIntervals[i] if (cursorE >= start) { cursorE = maxOf(cursorE, end) } else { ans.add(intArrayOf(cursorS, cursorE)) cursorS = start cursorE = end } } ans.add(intArrayOf(cursorS, cursorE)) return ans.toTypedArray() } }
반응형'ETC' 카테고리의 다른 글
[LeetCode / Kotlin] Remove Covered 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