g0001_0100.s0056_merge_intervals.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java21 Show documentation
Show all versions of leetcode-in-java21 Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
package g0001_0100.s0056_merge_intervals;
// #Medium #Top_100_Liked_Questions #Top_Interview_Questions #Array #Sorting
// #Data_Structure_II_Day_2_Array #Level_2_Day_17_Interval #Udemy_2D_Arrays/Matrix
// #Big_O_Time_O(n_log_n)_Space_O(n) #2023_08_11_Time_8_ms_(96.27%)_Space_45.2_MB_(90.13%)
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* 56 - Merge Intervals\.
*
* Medium
*
* 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
**/
public class Solution {
public int[][] merge(int[][] intervals) {
Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));
List list = new ArrayList<>();
int[] current = intervals[0];
list.add(current);
for (int[] next : intervals) {
if (current[1] >= next[0]) {
current[1] = Math.max(current[1], next[1]);
} else {
current = next;
list.add(current);
}
}
return list.toArray(new int[list.size()][]);
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy