056.Merge Intervals

Solution 1: accepted 28ms 59%

Time: O(2n)
Space: O(n)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution {
public List<Interval> merge(List<Interval> intervals) {
if (intervals.size() < 2)
return intervals;
List<Interval> result = new ArrayList<>();
Collections.sort(intervals, new IntervalComparator());
Interval temp = new Interval();
for (int i = 0; i < intervals.size() - 1; i++) {
if (intervals.get(i).end < intervals.get(i + 1).start) {
result.add(intervals.get(i));
} else if (intervals.get(i).start == intervals.get(i + 1).start) {
intervals.get(i + 1).end = Math.max(intervals.get(i).end, intervals.get(i + 1).end);
} else {
intervals.get(i + 1).start = intervals.get(i).start;
intervals.get(i + 1).end = Math.max(intervals.get(i).end, intervals.get(i + 1).end);
}
}
result.add(intervals.get(intervals.size() - 1));
return result;
}
private class IntervalComparator implements Comparator<Interval> {
public int compare(Interval a, Interval b) {
if (a.start < b.start)
return -1;
else if (a.start > b.start)
return 1;
else
return 0;
}
}
}
Simplified
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public List<Interval> merge(List<Interval> intervals) {
if (intervals.size() < 2)
return intervals;
List<Interval> result = new ArrayList<>();
Collections.sort(intervals, new Comparator<Interval>() {
public int compare(Interval a, Interval b) {
return a.start - b.start;
}
});
Interval temp = new Interval();
for (int i = 0; i < intervals.size() - 1; i++) {
Interval current = intervals.get(i);
Interval next = intervals.get(i + 1);
if (current.end < next.start) {
result.add(current);
} else {
next.start = current.start;
next.end = Math.max(current.end, next.end);
}
}
result.add(intervals.get(intervals.size() - 1));
return result;
}
}