You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
To solve the "Merge Intervals" problem in Java with the Solution class, follow these steps:
38
+
39
+
1. Define a method `merge` in the `Solution` class that takes an array of integer arrays `intervals` as input and returns an array of the non-overlapping intervals that cover all the intervals in the input.
40
+
2. Sort the intervals based on the start times.
41
+
3. Initialize an ArrayList to store the merged intervals.
42
+
4. Iterate through the sorted intervals:
43
+
- If the list of merged intervals is empty or the current interval's start time is greater than the end time of the last merged interval, add the current interval to the list of merged intervals.
44
+
- Otherwise, merge the current interval with the last merged interval by updating its end time if needed.
45
+
5. Convert the ArrayList of merged intervals into an array and return it as the result.
46
+
47
+
Here's the implementation of the `merge` method in Java:
48
+
49
+
```java
50
+
importjava.util.*;
51
+
52
+
classSolution {
53
+
publicint[][] merge(int[][] intervals) {
54
+
Arrays.sort(intervals, (a, b) ->Integer.compare(a[0], b[0]));
55
+
List<int[]> merged =newArrayList<>();
56
+
for (int[] interval : intervals) {
57
+
if (merged.isEmpty() || interval[0] > merged.get(merged.size() -1)[1]) {
This implementation efficiently merges overlapping intervals in the given array `intervals` using sorting and iteration, with a time complexity of O(n log n) due to sorting.
0 commit comments