题解 | #合并区间#
合并区间
http://www.nowcoder.com/practice/69f4e5b7ad284a478777cb2a17fb5e6a
方法:模拟
- 先对list进行排序
- 从list中拿出第i个和第i+1个
- 判断是否有重叠:(v1.start >= v2.start && v1.start <= v2.end) || (v2.start >= v1.start && v2.start <= v1.end)
public ArrayList<Interval> merge(ArrayList<Interval> intervals) {
Collections.sort(intervals, new Comparator<Interval>() {
@Override
public int compare(Interval o1, Interval o2) {
if (o1.start != o2.start) {
return o1.start - o2.start;
}else {
return o1.end - o2.end;
}
}
});
int i = 0;
while (i < intervals.size() - 1) {
Interval v1 = intervals.get(i);
Interval v2 = intervals.get(i + 1);
if ((v1.start >= v2.start && v1.start <= v2.end) || (v2.start >= v1.start && v2.start <= v1.end)) {
Interval newV = new Interval(Math.min(v1.start, v2.start), Math.max(v1.end, v2.end));
intervals.remove(i);
intervals.remove(i);
intervals.add(i, newV);
}else {
i++;
}
}
return intervals;
}
}