Merge pull request #16360 from sk1418/fix-merging-overlapping

[fix-merging-overlapping] fix
This commit is contained in:
Liam Williams 2024-04-13 15:32:16 +01:00 committed by GitHub
commit 6b4f48eb8f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 28 additions and 22 deletions

View File

@ -1,23 +1,22 @@
package com.baeldung.algorithms.mergeintervals;
import static java.lang.Integer.max;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class MergeOverlappingIntervals {
public List<Interval> doMerge(List<Interval> intervals) {
// Sort the intervals based on start time
intervals.sort((one, two) -> one.start - two.start);
// Create somewhere to put the merged list, start it off with the earliest starting interval
intervals.sort(Comparator.comparingInt(interval -> interval.start));
ArrayList<Interval> merged = new ArrayList<>();
merged.add(intervals.get(0));
// Loop over each interval and merge if start time is before the end time of the
// previous interval
intervals.forEach(interval -> {
if (merged.get(merged.size() - 1).end > interval.start) {
merged.get(merged.size() - 1).setEnd(interval.end);
Interval lastMerged = merged.get(merged.size() - 1);
if (interval.start <= lastMerged.end){
lastMerged.setEnd(max(interval.end, lastMerged.end));
} else {
merged.add(interval);
}
@ -25,5 +24,4 @@ public class MergeOverlappingIntervals {
return merged;
}
}

View File

@ -1,30 +1,38 @@
package com.baeldung.algorithms.mergeintervals;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Test;
class MergeIntervalsUnitTest {
private ArrayList<Interval> intervals = new ArrayList<>(Arrays.asList(
new Interval(2, 5),
private List<Interval> intervals = new ArrayList<>(Arrays.asList(
// @formatter:off
new Interval(3, 5),
new Interval(13, 20),
new Interval(11, 15),
new Interval(1, 3)
new Interval(15, 16),
new Interval(1, 3),
new Interval(4, 5),
new Interval(16, 17)
// @formatter:on
));
private ArrayList<Interval> intervalsMerged = new ArrayList<>(Arrays.asList(
private List<Interval> intervalsMerged = new ArrayList<>(Arrays.asList(
// @formatter:off
new Interval(1, 5),
new Interval(11, 20)
// @formatter:on
));
@Test
void givenIntervals_whenMerging_thenReturnMergedIntervals() {
MergeOverlappingIntervals merger = new MergeOverlappingIntervals();
ArrayList<Interval> result = (ArrayList<Interval>) merger.doMerge(intervals);
assertArrayEquals(intervalsMerged.toArray(), result.toArray());
List<Interval> result = merger.doMerge(intervals);
assertEquals(intervalsMerged, result);
}
}