/**
* 排序合并
*
* @author wuwang
*
*/
class Solution {
public List<Interval> merge(List<Interval> intervals) {
if (intervals == null || intervals.isEmpty())
return new LinkedList<>();
Interval[] arr = new Interval[intervals.size()];
for (int i = 0; i < arr.length; ++i) {
arr[i] = intervals.get(i);
}
Arrays.sort(arr, new Comparator<Interval>() {
@Override
public int compare(Interval o1, Interval o2) {
return Integer.valueOf(o1.start).compareTo(o2.start);
}
});
Deque<Interval> queue = new ArrayDeque<>(arr.length);
int i = 0;
queue.addLast(arr[i++]);
for (; i < arr.length; ++i) {
Interval interval = queue.pollLast();
// 可以合并
if (arr[i].start <= interval.end && arr[i].start >= interval.start) {
Interval newInterval = new Interval(interval.start, Math.max(interval.end, arr[i].end));
queue.add(newInterval);
} else {
queue.add(interval);
queue.add(arr[i]);
}
}
List<Interval> result = new LinkedList<>();
while (!queue.isEmpty()) {
result.add(queue.pop());
}
return result;
}
}
LeetCode56. 合并区间
最新推荐文章于 2023-05-09 23:54:15 发布