-
[Leetcode] 56. Merge Intervals코딩테스트 2021. 4. 27. 01:03
문제)
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] overlaps, 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
풀이)
1. Sorting
public int[][] merge(int[][] intervals) { Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0])); LinkedList<int[]> merged = new LinkedList<>(); for (int[] interval : intervals) { if (merged.isEmpty() || merged.getLast()[1] < interval[0]) { merged.add(interval); } else { merged.getLast()[1] = Math.max(merged.getLast()[1], interval[1]); } } return merged.toArray(new int[merged.size()][]); }
더보기1. 설명
- interval배열에서 row 기준으로 정렬
- merged라는 LinkedList의 마지막 값의 column(end값)과 현재 interval의 row(start값)을 비교하여 결과 정리
- 포함관계에 있다면, end값을 업데이트2. 제출결과
3. 시간복잡도
O(nlogn)
'코딩테스트' 카테고리의 다른 글
[Leetcode] 57. Insert Interval (0) 2021.05.02 [leetcode] 147. Insertion Sort List (0) 2021.04.29 [Leetcode] 395. Longest Substring with At Least K Repeating Characters (0) 2021.04.25 [Leetcode] 215. Kth Largest Element in an Array (0) 2021.04.24 [Leetcode] 240. Search a 2D Matrix II (0) 2021.04.20