Question
Solution
题目大意:
一个坐标轴,给你n个范围,把重叠的范围合并,返回合并后的坐标对
思路:
先排序,再遍历判断下一个开始是否在上一个范围内,如果在且结束坐标大于上一个坐标就合并
Java实现:
public List<Interval> merge(List<Interval> intervals) {
if (intervals == null || intervals.size() == 0) return intervals;
// sort
intervals = intervals.stream()
.sorted(Comparator.comparing(e -> e.start))
.collect(Collectors.toList());
List<Interval> result = new ArrayList<>();
int start = intervals.get(0).start;
int end = intervals.get(0).end;
for (int i = 1; i < intervals.size(); i++) {
Interval tmp = intervals.get(i);
if (tmp.start >= start && tmp.start <= end) {
if (tmp.end > end) end = tmp.end;
} else {
result.add(new Interval(start, end));
start = tmp.start;
end = tmp.end;
}
}
result.add(new Interval(start, end));
return result;
}
原文地址:https://www.cnblogs.com/okokabcd/p/9610368.html
时间: 2024-11-07 17:01:58