https://leetcode.com/problems/merge-intervals/#/description
Given a collection of intervals, merge all overlapping intervals.
For example,
Given [1,3],[2,6],[8,10],[15,18]
,
return [1,6],[8,10],[15,18]
.
Java Code:
package go.jacob.day626;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Demo3 {
/*
* Runtime: 25 ms.Your runtime beats 83.79 % of java submissions.
* 参考自:@danchou
*/
public List<Interval> merge(List<Interval> intervals) {
Collections.sort(intervals, new Comparator<Interval>() {
@Override
public int compare(Interval obj0, Interval obj1) {
return obj0.start - obj1.start;
}
});
List<Interval> ret = new ArrayList<>();
Interval prev = null;
for (Interval inter : intervals) {
if (prev == null || inter.start > prev.end) {
ret.add(inter);
prev = inter;
} else if (inter.end > prev.end) {
// Modify the element already in list
prev.end = inter.end;
}
}
return ret;
}
/*
* 首先对intervals中的元素进行排序(按start升序) 然后循环判断能否增加end
*
* Runtime: 27 ms.Your runtime beats 68.55 % of java submissions.
*/
public List<Interval> merge_byme(List<Interval> intervals) {
List<Interval> res = new ArrayList<Interval>();
if (intervals == null)
return res;
// 对intervals中元素进行排序
Collections.sort(intervals, new Comparator<Interval>() {
@Override
public int compare(Interval i1, Interval i2) {
return i1.start - i2.start;
}
});
int index = 0;
while (index < intervals.size()) {
Interval temp1 = intervals.get(index);
while (index != intervals.size() - 1) {
Interval temp2 = intervals.get(index + 1);
if (temp2.start <= temp1.end) {
index++;
if (temp2.end > temp1.end) {
temp1.end = temp2.end;
}
} else
break;
}
res.add(temp1);
index++;
}
return res;
}
}
class Interval {
int start;
int end;
Interval() {
start = 0;
end = 0;
}
Interval(int s, int e) {
start = s;
end = e;
}
}