Skip to content

Commit 7d5b484

Browse files
authored
Update readme.md
1 parent 0da853c commit 7d5b484

File tree

1 file changed

+34
-1
lines changed
  • src/main/java/g0001_0100/s0056_merge_intervals

1 file changed

+34
-1
lines changed

src/main/java/g0001_0100/s0056_merge_intervals/readme.md

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,4 +32,37 @@ Given an array of `intervals` where <code>intervals[i] = [start<sub>i</sub>, end
3232

3333
* <code>1 <= intervals.length <= 10<sup>4</sup></code>
3434
* `intervals[i].length == 2`
35-
* <code>0 <= start<sub>i</sub> <= end<sub>i</sub> <= 10<sup>4</sup></code>
35+
* <code>0 <= start<sub>i</sub> <= end<sub>i</sub> <= 10<sup>4</sup></code>
36+
37+
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+
import java.util.*;
51+
52+
class Solution {
53+
public int[][] merge(int[][] intervals) {
54+
Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));
55+
List<int[]> merged = new ArrayList<>();
56+
for (int[] interval : intervals) {
57+
if (merged.isEmpty() || interval[0] > merged.get(merged.size() - 1)[1]) {
58+
merged.add(interval);
59+
} else {
60+
merged.get(merged.size() - 1)[1] = Math.max(merged.get(merged.size() - 1)[1], interval[1]);
61+
}
62+
}
63+
return merged.toArray(new int[merged.size()][]);
64+
}
65+
}
66+
```
67+
68+
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

Comments
 (0)