File tree Expand file tree Collapse file tree 3 files changed +77
-1
lines changed
test/java/leetcode/mergeintervals Expand file tree Collapse file tree 3 files changed +77
-1
lines changed Original file line number Diff line number Diff line change 1
1
package leetcode .meetingrooms ;
2
2
3
3
public class Interval {
4
- public final int start ;
4
+ public int start ;
5
5
public int end ;
6
6
7
7
public Interval () {
@@ -13,4 +13,18 @@ public Interval(int s, int e) {
13
13
start = s ;
14
14
end = e ;
15
15
}
16
+
17
+ @ Override
18
+ public String toString () {
19
+ return "[" + start + ", " + end + "]" ;
20
+ }
21
+
22
+ @ Override
23
+ public boolean equals (Object obj ) {
24
+ if (!(obj instanceof Interval )) {
25
+ return false ;
26
+ }
27
+ Interval o = (Interval ) obj ;
28
+ return start == o .start && end == o .end ;
29
+ }
16
30
}
Original file line number Diff line number Diff line change
1
+ package leetcode.mergeintervals
2
+
3
+ import leetcode.meetingrooms.Interval
4
+
5
+ /* *
6
+ * https://leetcode.com/problems/merge-intervals/description/
7
+ */
8
+ class Solution {
9
+ fun merge (intervals : List <Interval >): List <Interval > = when {
10
+ intervals.isEmpty() -> emptyList()
11
+ else -> {
12
+ val sortedIntervals = intervals.sortedBy { it.start }
13
+ val mergedIntervals = mutableListOf<Interval >()
14
+ mergedIntervals + = sortedIntervals.first()
15
+
16
+ (1 .. sortedIntervals.lastIndex).forEach {
17
+ val current = mergedIntervals.last()
18
+ val next = sortedIntervals[it]
19
+ when {
20
+ current.end >= next.start -> {
21
+ // e.g. [1,4] and [2,3] -> [1,4]
22
+ current.end = maxOf(current.end, next.end)
23
+ }
24
+ else -> mergedIntervals + = next
25
+ }
26
+ }
27
+ mergedIntervals
28
+ }
29
+ }
30
+ }
Original file line number Diff line number Diff line change
1
+ package leetcode.mergeintervals
2
+
3
+ import leetcode.meetingrooms.Interval
4
+ import org.amshove.kluent.shouldEqual
5
+ import org.junit.Test
6
+
7
+ class SolutionTest {
8
+ @Test
9
+ fun test () {
10
+ Solution ().merge(listOf (
11
+ Interval (1 , 3 ),
12
+ Interval (2 , 6 ),
13
+ Interval (8 , 10 ),
14
+ Interval (15 , 18 )
15
+ )).shouldEqual(listOf (
16
+ Interval (1 , 6 ),
17
+ Interval (8 , 10 ),
18
+ Interval (15 , 18 )
19
+ ))
20
+ Solution ().merge(listOf (
21
+ Interval (1 , 4 ),
22
+ Interval (2 , 3 )
23
+ )).shouldEqual(listOf (
24
+ Interval (1 , 4 )
25
+ ))
26
+ Solution ().merge(listOf (
27
+ Interval (1 , 3 )
28
+ )).shouldEqual(listOf (
29
+ Interval (1 , 3 )
30
+ ))
31
+ }
32
+ }
You can’t perform that action at this time.
0 commit comments